1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-12 08:23:58 +02:00
go-micro/data/store/consul/consul.go

97 lines
1.8 KiB
Go
Raw Normal View History

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