forked from docker/libkv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libkv.go
102 lines (96 loc) · 2.68 KB
/
libkv.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
// Package libkv provides a Go native library to store metadata.
//
// The goal of libkv is to abstract common store operations for multiple
// Key/Value backends and offer the same experience no matter which one of the
// backend you want to use.
//
// For example, you can use it to store your metadata or for service discovery to
// register machines and endpoints inside your cluster.
//
// As of now, `libkv` offers support for `Consul`, `Etcd` and `Zookeeper`.
//
// ## Example of usage
//
// ### Create a new store and use Put/Get
//
//
// package main
//
// import (
// "fmt"
// "time"
//
// "github.com/gonkulator/libkv"
// "github.com/gonkulator/libkv/store"
// log "github.com/Sirupsen/logrus"
// )
//
// func main() {
// client := "localhost:8500"
//
// // Initialize a new store with consul
// kv, err := libkv.NewStore(
// store.CONSUL, // or "consul"
// []string{client},
// &store.Config{
// ConnectionTimeout: 10*time.Second,
// },
// )
// if err != nil {
// log.Fatal("Cannot create store consul")
// }
//
// key := "foo"
// err = kv.Put(key, []byte("bar"), nil)
// if err != nil {
// log.Error("Error trying to put value at key `", key, "`")
// }
//
// pair, err := kv.Get(key)
// if err != nil {
// log.Error("Error trying accessing value at key `", key, "`")
// }
//
// log.Info("value: ", string(pair.Value))
// }
//
// ##Copyright and license
//
// Code and documentation copyright 2015 Docker, inc. Code released under the
// Apache 2.0 license. Docs released under Creative commons.
//
package libkv
import (
"fmt"
"sort"
"strings"
"github.com/gonkulator/libkv/store"
"github.com/gonkulator/libkv/store/consul"
"github.com/gonkulator/libkv/store/etcd"
"github.com/gonkulator/libkv/store/zookeeper"
)
// Initialize creates a new Store object, initializing the client
type Initialize func(addrs []string, options *store.Config) (store.Store, error)
var (
// Backend initializers
initializers = map[store.Backend]Initialize{
store.CONSUL: consul.New,
store.ETCD: etcd.New,
store.ZK: zookeeper.New,
}
supportedBackend = func() string {
keys := make([]string, 0, len(initializers))
for k := range initializers {
keys = append(keys, string(k))
}
sort.Strings(keys)
return strings.Join(keys, ", ")
}()
)
// NewStore creates a an instance of store
func NewStore(backend store.Backend, addrs []string, options *store.Config) (store.Store, error) {
if init, exists := initializers[backend]; exists {
return init(addrs, options)
}
return nil, fmt.Errorf("%s %s", store.ErrNotSupported.Error(), supportedBackend)
}