/
kv.go
62 lines (53 loc) · 1.55 KB
/
kv.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
package KeyValueStoreFilter
import (
"fmt"
"time"
"gopkg.in/flosch/pongo2.v3"
"github.com/docker/libkv"
"github.com/docker/libkv/store"
"github.com/docker/libkv/store/boltdb"
"github.com/docker/libkv/store/consul"
"github.com/docker/libkv/store/etcd"
"github.com/docker/libkv/store/zookeeper"
"github.com/odedlaz/tpl/template"
)
func init() {
consul.Register()
etcd.Register()
zookeeper.Register()
boltdb.Register()
template.RegisterFilter("kvget", get)
}
func get(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
key := in.String()
kv, err := libkv.NewStore(
store.Backend(template.Settings.KV.Type),
[]string{template.Settings.KV.URL},
&store.Config{
ClientTLS: template.Settings.KV.ClientTLS,
TLS: template.Settings.KV.TLS,
Bucket: template.Settings.KV.Bucket,
Username: template.Settings.KV.Username,
Password: template.Settings.KV.Password,
PersistConnection: template.Settings.KV.PersistConnection,
ConnectionTimeout: time.Duration(template.Settings.KV.ConnectionTimeout) * time.Second,
},
)
if err != nil {
return nil, &pongo2.Error{
Sender: "filter:kv",
ErrorMsg: fmt.Sprintf("Error creating kv client: %s", err.Error()),
}
}
pair, err := kv.Get(key)
if err != nil && param.IsNil() {
return nil, &pongo2.Error{
Sender: "filter:kv",
ErrorMsg: fmt.Sprintf("Error trying accessing value at key: %v", key),
}
}
if err != nil {
return pongo2.AsValue(param.String()), nil
}
return pongo2.AsValue(string(pair.Value)), nil
}