Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. package main
  2. import (
  3. "fmt"
  4. consulApi "github.com/hashicorp/consul/api"
  5. "github.com/sirupsen/logrus"
  6. "log"
  7. "strings"
  8. "time"
  9. )
  10.  
  11.  
  12. func ToMap(consulSpec *consulApi.Config, offset string, keysWithOffset ...bool) (map[string]string, error) {
  13.  
  14. consul, err := consulApi.NewClient(consulSpec)
  15. if err != nil {
  16. return nil, err
  17. }
  18.  
  19. kv := consul.KV()
  20.  
  21. config := make(map[string]string)
  22.  
  23. kvps, _, err := kv.List(offset, nil)
  24. if err != nil {
  25. return nil, fmt.Errorf("failed to fetch k/v pairs from consul: %+v, path offset: %s. due to %v", consulSpec, offset, err)
  26. }
  27.  
  28. withOffset := true
  29. if len(keysWithOffset) > 0 {
  30. withOffset = keysWithOffset[0]
  31. }
  32.  
  33. for _, kvp := range kvps {
  34. if val := kvp.Value; val != nil {
  35. k := kvp.Key
  36. if !withOffset {
  37. k = strings.Split(kvp.Key, offset)[1]
  38. }
  39. config[k] = string(val[:])
  40. }
  41. }
  42.  
  43. log.Printf("read consul map at key: /%s\n", offset)
  44. for _, v := range config {
  45. log.Printf("%s", v)
  46. }
  47. return config, nil
  48. }
  49.  
  50. func ToConsul(consulSpec *consulApi.Config, config map[string]string) (time.Duration, error) {
  51.  
  52. consul, err := consulApi.NewClient(consulSpec)
  53. if err != nil {
  54. return 0, err
  55. }
  56.  
  57. kv := consul.KV()
  58.  
  59. var duration time.Duration
  60.  
  61. for k, v := range config {
  62. took, err := kv.Put(&consulApi.KVPair{Key: k, Value: []byte(v)}, nil)
  63. if err != nil {
  64. return 0, fmt.Errorf("could not put a key, value: {%s, %s} to consul %+v due to %v", k, v, consulSpec, err)
  65. }
  66. duration += took.RequestTime
  67. }
  68.  
  69. return duration, nil
  70. }
  71.  
  72. func main(){
  73. config := consulApi.DefaultConfig()
  74. config.Address = "192.168.1.2:18500"
  75. toMap, err := consul.ToMap(config, "we-key")
  76. if err != nil {
  77. fmt.Println(err.Error())
  78. }
  79. fmt.Println(toMap)
  80. v := toMap["we-key"]
  81. setting := conf.Setting{}
  82. err = yaml.Unmarshal([]byte(v), &setting)
  83. fmt.Println(setting.LogLevel)
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement