diff --git a/config/remote/etcd/etcd.go b/config/remote/etcd/etcd.go index 2a997419..16575e8b 100644 --- a/config/remote/etcd/etcd.go +++ b/config/remote/etcd/etcd.go @@ -5,7 +5,9 @@ import ( "context" "errors" "fmt" - + "github.com/DoNewsCode/core" + "github.com/DoNewsCode/core/config" + "github.com/DoNewsCode/core/contract" "go.etcd.io/etcd/client/v3" ) @@ -17,13 +19,20 @@ type ETCD struct { } // Provider create a *ETCD -func Provider(key string, clientConfig *clientv3.Config) *ETCD { +func Provider(clientConfig *clientv3.Config, key string) *ETCD { return &ETCD{ key: key, clientConfig: clientConfig, } } +// WithKey is a two-in-one coreOption. It uses the remote key on etcd as the +// source of configuration, and watches the change of that key for hot reloading. +func WithKey(cfg *clientv3.Config, key string, codec contract.Codec) (core.CoreOption, core.CoreOption) { + r := Provider(cfg, key) + return core.WithConfigStack(r, config.CodecParser{Codec: codec}), core.WithConfigWatcher(r) +} + // ReadBytes reads the contents of a key from etcd and returns the bytes. func (r *ETCD) ReadBytes() ([]byte, error) { client, err := clientv3.New(*r.clientConfig) diff --git a/config/remote/etcd/example_test.go b/config/remote/etcd/example_test.go index a24c4c1f..d05fc3dd 100644 --- a/config/remote/etcd/example_test.go +++ b/config/remote/etcd/example_test.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/DoNewsCode/core" "github.com/DoNewsCode/core/codec/yaml" - "github.com/DoNewsCode/core/config" "github.com/DoNewsCode/core/config/remote/etcd" clientv3 "go.etcd.io/etcd/client/v3" "os" @@ -21,14 +20,13 @@ func Example() { } key := "core.yaml" envEtcdAddrs := strings.Split(addr, ",") - cfg := clientv3.Config{ + cfg := &clientv3.Config{ Endpoints: envEtcdAddrs, DialTimeout: time.Second, } _ = put(cfg, key, "name: etcd") - provider := etcd.Provider(key, &cfg) - c := core.New(core.WithConfigStack(provider, config.CodecParser{Codec: yaml.Codec{}}), core.WithConfigWatcher(provider)) + c := core.New(etcd.WithKey(cfg, key, yaml.Codec{})) c.ProvideEssentials() fmt.Println(c.String("name")) @@ -36,8 +34,8 @@ func Example() { // etcd } -func put(cfg clientv3.Config, key, val string) error { - client, err := clientv3.New(cfg) +func put(cfg *clientv3.Config, key, val string) error { + client, err := clientv3.New(*cfg) if err != nil { return err }