micro/store/etcd/etcd.go

71 lines
1.1 KiB
Go
Raw Normal View History

package etcd
2015-02-07 23:12:57 +03:00
import (
"errors"
"github.com/coreos/go-etcd/etcd"
"github.com/myodc/go-micro/store"
2015-02-07 23:12:57 +03:00
)
type estore struct {
2015-02-07 23:12:57 +03:00
Client *etcd.Client
}
type item struct {
key string
value []byte
}
func (i *item) Key() string {
return i.key
}
func (i *item) Value() []byte {
return i.value
}
func (e *estore) Get(key string) (store.Item, error) {
2015-02-07 23:12:57 +03:00
kv, err := e.Client.Get(key, false, false)
if err != nil {
return nil, err
}
if kv == nil {
return nil, errors.New("key not found")
}
return &item{
2015-02-07 23:12:57 +03:00
key: kv.Node.Key,
value: []byte(kv.Node.Value),
}, nil
}
func (e *estore) Del(key string) error {
2015-02-07 23:12:57 +03:00
_, err := e.Client.Delete(key, false)
return err
}
func (e *estore) Put(item store.Item) error {
2015-02-07 23:12:57 +03:00
_, err := e.Client.Set(item.Key(), string(item.Value()), 0)
return err
}
func (e *estore) NewItem(key string, value []byte) store.Item {
return &item{
2015-02-07 23:12:57 +03:00
key: key,
value: value,
}
}
func NewStore(addrs []string, opts ...store.Option) store.Store {
if len(addrs) == 0 {
addrs = []string{"127.0.0.1:2379"}
}
client := etcd.NewClient(addrs)
2015-02-07 23:12:57 +03:00
return &estore{
2015-02-07 23:12:57 +03:00
Client: client,
}
}