-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
89 lines (75 loc) · 1.53 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package consul
import (
"context"
"errors"
"path/filepath"
"strings"
"github.com/go-kratos/kratos/v2/config"
"github.com/hashicorp/consul/api"
)
// Option is consul config option.
type Option func(o *options)
type options struct {
ctx context.Context
path string
}
// WithContext with registry context.
func WithContext(ctx context.Context) Option {
return func(o *options) {
o.ctx = ctx
}
}
// WithPath is config path
func WithPath(p string) Option {
return func(o *options) {
o.path = p
}
}
type source struct {
client *api.Client
options *options
}
func New(client *api.Client, opts ...Option) (config.Source, error) {
o := &options{
ctx: context.Background(),
path: "",
}
for _, opt := range opts {
opt(o)
}
if o.path == "" {
return nil, errors.New("path invalid")
}
return &source{
client: client,
options: o,
}, nil
}
// Load return the config values
func (s *source) Load() ([]*config.KeyValue, error) {
kv, _, err := s.client.KV().List(s.options.path, nil)
if err != nil {
return nil, err
}
pathPrefix := s.options.path
if !strings.HasSuffix(s.options.path, "/") {
pathPrefix = pathPrefix + "/"
}
kvs := make([]*config.KeyValue, 0)
for _, item := range kv {
k := strings.TrimPrefix(item.Key, pathPrefix)
if k == "" {
continue
}
kvs = append(kvs, &config.KeyValue{
Key: k,
Value: item.Value,
Format: strings.TrimPrefix(filepath.Ext(k), "."),
})
}
return kvs, nil
}
// Watch return the watcher
func (s *source) Watch() (config.Watcher, error) {
return newWatcher(s)
}