micro/store/consul/consul.go

97 lines
1.8 KiB
Go
Raw Normal View History

2019-05-31 00:43:23 +01:00
// Package consul is a consul implementation of kv
package consul
import (
"fmt"
"net"
"github.com/hashicorp/consul/api"
2019-06-12 12:45:42 +01:00
"github.com/micro/go-micro/config/options"
2019-06-12 07:46:20 +01:00
"github.com/micro/go-micro/store"
2019-05-31 00:43:23 +01:00
)
type ckv struct {
2019-06-11 17:20:52 +01:00
options.Options
2019-05-31 00:43:23 +01:00
client *api.Client
}
2019-06-12 07:46:20 +01:00
func (c *ckv) Read(key string) (*store.Record, error) {
2019-05-31 00:43:23 +01:00
keyval, _, err := c.client.KV().Get(key, nil)
if err != nil {
return nil, err
}
if keyval == nil {
2019-06-12 07:46:20 +01:00
return nil, store.ErrNotFound
2019-05-31 00:43:23 +01:00
}
2019-06-12 07:46:20 +01:00
return &store.Record{
2019-05-31 00:43:23 +01:00
Key: keyval.Key,
Value: keyval.Value,
}, nil
}
func (c *ckv) Delete(key string) error {
_, err := c.client.KV().Delete(key, nil)
return err
}
2019-06-12 07:46:20 +01:00
func (c *ckv) Write(record *store.Record) error {
2019-05-31 00:43:23 +01:00
_, err := c.client.KV().Put(&api.KVPair{
Key: record.Key,
Value: record.Value,
}, nil)
return err
}
2019-06-12 07:46:20 +01:00
func (c *ckv) Dump() ([]*store.Record, error) {
2019-05-31 00:43:23 +01:00
keyval, _, err := c.client.KV().List("/", nil)
if err != nil {
return nil, err
}
if keyval == nil {
2019-06-12 07:46:20 +01:00
return nil, store.ErrNotFound
2019-05-31 00:43:23 +01:00
}
2019-06-12 07:46:20 +01:00
var vals []*store.Record
2019-05-31 00:43:23 +01:00
for _, keyv := range keyval {
2019-06-12 07:46:20 +01:00
vals = append(vals, &store.Record{
2019-05-31 00:43:23 +01:00
Key: keyv.Key,
Value: keyv.Value,
})
}
return vals, nil
}
func (c *ckv) String() string {
return "consul"
}
2019-06-12 07:46:20 +01:00
func NewStore(opts ...options.Option) store.Store {
2019-06-11 17:20:52 +01:00
options := options.NewOptions(opts...)
2019-05-31 00:43:23 +01:00
config := api.DefaultConfig()
2019-06-11 17:20:52 +01:00
var nodes []string
2019-06-12 07:46:20 +01:00
if n, ok := options.Values().Get("store.nodes"); ok {
2019-06-11 17:20:52 +01:00
nodes = n.([]string)
}
2019-05-31 00:43:23 +01:00
// set host
2019-06-11 17:20:52 +01:00
if len(nodes) > 0 {
addr, port, err := net.SplitHostPort(nodes[0])
2019-05-31 00:43:23 +01:00
if ae, ok := err.(*net.AddrError); ok && ae.Err == "missing port in address" {
port = "8500"
2019-06-11 17:20:52 +01:00
config.Address = fmt.Sprintf("%s:%s", nodes[0], port)
2019-05-31 00:43:23 +01:00
} else if err == nil {
config.Address = fmt.Sprintf("%s:%s", addr, port)
}
}
client, _ := api.NewClient(config)
return &ckv{
2019-06-11 17:20:52 +01:00
Options: options,
client: client,
2019-05-31 00:43:23 +01:00
}
}