-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconsul.go
133 lines (108 loc) · 2.47 KB
/
consul.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// Methods which interact directly with Consul. Should isolate the
// code for consul here.
package jsonconsul
import (
"encoding/json"
"fmt"
"github.com/hashicorp/consul/api"
"log"
"strings"
)
var (
client *api.Client
kv *api.KV
)
func interfaceToConsulFlattenedMap(nested interface{}, prefix string, output map[string]interface{}) {
for k, v := range nested.(map[string]interface{}) {
newPrefix := fmt.Sprintf("%s/%s", prefix, k)
switch v.(type) {
case map[string]interface{}:
interfaceToConsulFlattenedMap(v, newPrefix, output)
default:
output[newPrefix] = v
}
}
}
func consulToFlattenedMap(prefix string) (map[string]interface{}, error) {
output := make(map[string]interface{})
nested, err := consulToNestedMap(prefix, true)
if err != nil {
return nil, err
}
interfaceToConsulFlattenedMap(nested, prefix, output)
return output, nil
}
func consulToNestedMap(prefix string, includePrefix bool) (v map[string]interface{}, err error) {
v = make(map[string]interface{})
kv := client.KV() // Lookup the pair
pairs, _, err := kv.List(prefix, nil)
if err != nil {
return v, err
}
for _, n := range pairs {
keyIter := v
keys := strings.Split(n.Key, "/")
for i, key := range keys {
if i == len(keys)-1 {
keyIter[key] = string(n.Value)
} else {
if _, ok := keyIter[key]; !ok {
keyIter[key] = make(map[string]interface{})
}
keyIter = keyIter[key].(map[string]interface{})
}
}
}
if !includePrefix {
nodes := strings.Split(prefix, "/")
for _, node := range nodes {
switch v[node].(type) {
case map[string]interface{}:
v, _ = v[node].(map[string]interface{})
}
}
}
return v, nil
}
func consulPrefixedKey(prefix, key string) (newKey string) {
if prefix == "" {
newKey = key
} else {
newKey = fmt.Sprintf("%s/%s", prefix, strings.TrimPrefix(key, "/"))
}
newKey = strings.TrimPrefix(newKey, "/")
return
}
func setConsulKVs(prefix string, kvMap map[string]interface{}) error {
for k, v := range kvMap {
value, err := json.Marshal(v)
if err != nil {
return err
}
if err := setConsulKV(consulPrefixedKey(prefix, k), value); err != nil {
return err
}
}
return nil
}
func setConsulKV(key string, value []byte) error {
p := &api.KVPair{
Key: key,
Value: value,
}
_, err := kv.Put(p, nil)
if err != nil {
return err
}
return nil
}
func init() {
var (
err error
)
client, err = api.NewClient(api.DefaultConfig())
if err != nil {
log.Fatalln(err)
}
kv = client.KV()
}