forked from bubunyo/config-watcher
/
api.go
52 lines (43 loc) · 997 Bytes
/
api.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
package consul
import (
"context"
"errors"
"github.com/bubunyo/config-watcher/common"
"github.com/bubunyo/config-watcher/internal"
"github.com/hashicorp/consul/api"
"net/http"
)
type Config struct {
common.Config
// Address is the address of the Consul server
Address string
}
type consul struct {
kv *api.KV
}
// NewWatcher returns a new Watcher for watching keys on consul
func NewWatcher(c *Config) (internal.Watcher, error) {
client, err := api.NewClient(&api.Config{
Address: c.Address,
HttpClient: &http.Client{Timeout: c.PollInterval},
})
if err != nil {
return nil, err
}
consul := &consul{kv: client.KV()}
wi, err := internal.NewWatcher("consul", &c.Config, consul)
if err != nil {
return nil, err
}
return wi, nil
}
func (c consul) Get(_ context.Context, key string) ([]byte, error) {
pair, _, err := c.kv.Get(key, nil)
if err != nil {
return nil, err
}
if pair == nil {
return nil, errors.New("key not found")
}
return pair.Value, nil
}