Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- consulApi "github.com/hashicorp/consul/api"
- "github.com/sirupsen/logrus"
- "log"
- "strings"
- "time"
- )
- func ToMap(consulSpec *consulApi.Config, offset string, keysWithOffset ...bool) (map[string]string, error) {
- consul, err := consulApi.NewClient(consulSpec)
- if err != nil {
- return nil, err
- }
- kv := consul.KV()
- config := make(map[string]string)
- kvps, _, err := kv.List(offset, nil)
- if err != nil {
- return nil, fmt.Errorf("failed to fetch k/v pairs from consul: %+v, path offset: %s. due to %v", consulSpec, offset, err)
- }
- withOffset := true
- if len(keysWithOffset) > 0 {
- withOffset = keysWithOffset[0]
- }
- for _, kvp := range kvps {
- if val := kvp.Value; val != nil {
- k := kvp.Key
- if !withOffset {
- k = strings.Split(kvp.Key, offset)[1]
- }
- config[k] = string(val[:])
- }
- }
- log.Printf("read consul map at key: /%s\n", offset)
- for _, v := range config {
- log.Printf("%s", v)
- }
- return config, nil
- }
- func ToConsul(consulSpec *consulApi.Config, config map[string]string) (time.Duration, error) {
- consul, err := consulApi.NewClient(consulSpec)
- if err != nil {
- return 0, err
- }
- kv := consul.KV()
- var duration time.Duration
- for k, v := range config {
- took, err := kv.Put(&consulApi.KVPair{Key: k, Value: []byte(v)}, nil)
- if err != nil {
- return 0, fmt.Errorf("could not put a key, value: {%s, %s} to consul %+v due to %v", k, v, consulSpec, err)
- }
- duration += took.RequestTime
- }
- return duration, nil
- }
- func main(){
- config := consulApi.DefaultConfig()
- config.Address = "192.168.1.2:18500"
- toMap, err := consul.ToMap(config, "we-key")
- if err != nil {
- fmt.Println(err.Error())
- }
- fmt.Println(toMap)
- v := toMap["we-key"]
- setting := conf.Setting{}
- err = yaml.Unmarshal([]byte(v), &setting)
- fmt.Println(setting.LogLevel)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement