diff --git a/etcd/common.go b/etcd/common.go index d9595d1..078da91 100644 --- a/etcd/common.go +++ b/etcd/common.go @@ -88,6 +88,14 @@ func WithTLSOpt(certFile, keyFile, caFile string) Option { } } +// WithAuthOpt returns an option that authentication by username and password. +func WithAuthOpt(username, password string) Option { + return func(cfg *clientv3.Config) { + cfg.Username = username + cfg.Password = password + } +} + func newTLSConfig(certFile, keyFile, caFile, serverName string) (*tls.Config, error) { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { diff --git a/etcd/readme.md b/etcd/readme.md index 82687f2..09cf3e9 100644 --- a/etcd/readme.md +++ b/etcd/readme.md @@ -93,8 +93,6 @@ make prepare make prepare-cluster ``` - - ### run server ```go @@ -120,6 +118,80 @@ go run ./example/client/main.go 2022/08/23 21:11:29.115257 main.go:57: [Info] code=200,body={"ping":"pong2"} ``` +## Authentication + +### Server + +```go +package main + +import ( + "context" + + "github.com/cloudwego/hertz/pkg/app" + "github.com/cloudwego/hertz/pkg/app/server" + "github.com/cloudwego/hertz/pkg/app/server/registry" + "github.com/cloudwego/hertz/pkg/common/utils" + "github.com/cloudwego/hertz/pkg/protocol/consts" + "github.com/hertz-contrib/registry/etcd" +) + +func main() { + r, err := etcd.NewEtcdRegistry([]string{"127.0.0.1:2379"}, etcd.WithAuthOpt("root", "123456")) + if err != nil { + panic(err) + } + addr := "127.0.0.1:8888" + h := server.Default( + server.WithHostPorts(addr), + server.WithRegistry(r, ®istry.Info{ + ServiceName: "hertz.test.demo", + Addr: utils.NewNetAddr("tcp", addr), + Weight: 10, + Tags: nil, + })) + h.GET("/ping", func(_ context.Context, ctx *app.RequestContext) { + ctx.JSON(consts.StatusOK, utils.H{"ping": "pong2"}) + }) + h.Spin() +} +``` + +### Client + +```go +package main + +import ( + "context" + + "github.com/cloudwego/hertz/pkg/app/client" + "github.com/cloudwego/hertz/pkg/app/middlewares/client/sd" + "github.com/cloudwego/hertz/pkg/common/config" + "github.com/cloudwego/hertz/pkg/common/hlog" + "github.com/hertz-contrib/registry/etcd" +) + +func main() { + cli, err := client.NewClient() + if err != nil { + panic(err) + } + r, err := etcd.NewEtcdResolver([]string{"127.0.0.1:2379"}, etcd.WithAuthOpt("root", "123456")) + if err != nil { + panic(err) + } + cli.Use(sd.Discovery(r)) + for i := 0; i < 10; i++ { + status, body, err := cli.Get(context.Background(), nil, "http://hertz.test.demo/ping", config.WithSD(true)) + if err != nil { + hlog.Fatal(err) + } + hlog.Infof("HERTZ: code=%d,body=%s", status, string(body)) + } +} +``` + ## Compatibility Compatible with server (3.0.0 - 3.5.4)