Skip to content

Commit

Permalink
feat: add WithKey helper
Browse files Browse the repository at this point in the history
  • Loading branch information
Reasno committed Aug 6, 2021
1 parent f705cf6 commit d16c9e5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
13 changes: 11 additions & 2 deletions config/remote/etcd/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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)
Expand Down
10 changes: 4 additions & 6 deletions config/remote/etcd/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -21,23 +20,22 @@ 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"))

// Output:
// 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
}
Expand Down

0 comments on commit d16c9e5

Please sign in to comment.