Skip to content

Commit

Permalink
feat: add auth support in address configuration for etcd registry (#3439
Browse files Browse the repository at this point in the history
)
  • Loading branch information
xxxwang1983 committed Mar 29, 2024
1 parent 1e7d897 commit 509fdf4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
36 changes: 32 additions & 4 deletions contrib/registry/etcd/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
package etcd

import (
"strings"
"time"

etcd3 "go.etcd.io/etcd/client/v3"
Expand Down Expand Up @@ -45,14 +46,41 @@ const (
)

// New creates and returns a new etcd registry.
// Support Etcd Address format: ip:port,ip:port...,ip:port@username:password
func New(address string, option ...Option) gsvc.Registry {
endpoints := gstr.SplitAndTrim(address, ",")
if address == "" {
panic(gerror.NewCode(gcode.CodeInvalidParameter, `invalid etcd address ""`))
}
addressAndAuth := gstr.SplitAndTrim(address, "@")
var (
endpoints []string
userName, password string
)
switch len(addressAndAuth) {
case 1:
endpoints = gstr.SplitAndTrim(address, ",")
default:
endpoints = gstr.SplitAndTrim(addressAndAuth[0], ",")
parts := gstr.SplitAndTrim(strings.Join(addressAndAuth[1:], "@"), ":")
switch len(parts) {
case 2:
userName = parts[0]
password = parts[1]
default:
panic(gerror.NewCode(gcode.CodeInvalidParameter, `invalid etcd auth not support ":" at username or password `))
}
}
if len(endpoints) == 0 {
panic(gerror.NewCodef(gcode.CodeInvalidParameter, `invalid etcd address "%s"`, address))
}
client, err := etcd3.New(etcd3.Config{
Endpoints: endpoints,
})
cfg := etcd3.Config{Endpoints: endpoints}
if userName != "" {
cfg.Username = userName
}
if password != "" {
cfg.Password = password
}
client, err := etcd3.New(cfg)
if err != nil {
panic(gerror.Wrap(err, `create etcd client failed`))
}
Expand Down
4 changes: 2 additions & 2 deletions contrib/registry/etcd/etcd_z_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
func TestRegistry(t *testing.T) {
var (
ctx = gctx.GetInitCtx()
registry = etcd.New(`127.0.0.1:2379`)
registry = etcd.New(`127.0.0.1:2379@root:123`)
)
svc := &gsvc.LocalService{
Name: guid.S(),
Expand Down Expand Up @@ -86,7 +86,7 @@ func TestRegistry(t *testing.T) {
func TestWatch(t *testing.T) {
var (
ctx = gctx.GetInitCtx()
registry = etcd.New(`127.0.0.1:2379`)
registry = etcd.New(`127.0.0.1:2379@root:123`)
)

svc1 := &gsvc.LocalService{
Expand Down

0 comments on commit 509fdf4

Please sign in to comment.