Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add auth support in address configuration for etcd registry #3439

Merged
merged 2 commits into from
Mar 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading