micro/store/consul_store.go

61 lines
1012 B
Go
Raw Normal View History

2015-01-13 23:31:27 +00:00
package store
import (
"errors"
consul "github.com/hashicorp/consul/api"
2015-01-13 23:31:27 +00:00
)
type ConsulStore struct {
Client *consul.Client
}
func (c *ConsulStore) Get(key string) (Item, error) {
kv, _, err := c.Client.KV().Get(key, nil)
if err != nil {
return nil, err
}
if kv == nil {
return nil, errors.New("key not found")
}
return &ConsulItem{
key: kv.Key,
value: kv.Value,
}, nil
}
func (c *ConsulStore) Del(key string) error {
_, err := c.Client.KV().Delete(key, nil)
return err
}
func (c *ConsulStore) Put(item Item) error {
_, err := c.Client.KV().Put(&consul.KVPair{
Key: item.Key(),
Value: item.Value(),
}, nil)
return err
}
func (c *ConsulStore) NewItem(key string, value []byte) Item {
return &ConsulItem{
key: key,
value: value,
}
}
func NewConsulStore(addrs []string, opts ...Options) Store {
config := consul.DefaultConfig()
if len(addrs) > 0 {
config.Address = addrs[0]
}
client, _ := consul.NewClient(config)
2015-01-13 23:31:27 +00:00
return &ConsulStore{
Client: client,
}
}