Converge etcd functionality as part of quick.Config

This commit is contained in:
Harshavardhana
2018-04-23 11:05:56 -07:00
committed by kannappanr
parent 6df1e4a529
commit 481390d51a
10 changed files with 164 additions and 317 deletions

View File

@@ -20,6 +20,7 @@ package quick
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
@@ -27,7 +28,9 @@ import (
"path/filepath"
"runtime"
"strings"
"time"
etcd "github.com/coreos/etcd/client"
yaml "gopkg.in/yaml.v2"
)
@@ -122,6 +125,55 @@ func saveFileConfig(filename string, v interface{}) error {
}
func saveFileConfigEtcd(filename string, clnt etcd.Client, v interface{}) error {
// Fetch filename's extension
ext := filepath.Ext(filename)
// Marshal data
dataBytes, err := toMarshaller(ext)(v)
if err != nil {
return err
}
if runtime.GOOS == "windows" {
dataBytes = []byte(strings.Replace(string(dataBytes), "\n", "\r\n", -1))
}
kapi := etcd.NewKeysAPI(clnt)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
_, err = kapi.Update(ctx, filename, string(dataBytes))
cancel()
return err
}
func loadFileConfigEtcd(filename string, clnt etcd.Client, v interface{}) error {
kapi := etcd.NewKeysAPI(clnt)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
resp, err := kapi.Get(ctx, filename, nil)
cancel()
if err != nil {
return err
}
var ev *etcd.Node
switch {
case resp.Node.Dir:
for _, ev = range resp.Node.Nodes {
if string(ev.Key) == filename {
break
}
}
default:
ev = resp.Node
}
fileData := ev.Value
if runtime.GOOS == "windows" {
fileData = strings.Replace(ev.Value, "\r\n", "\n", -1)
}
// Unmarshal file's content
return toUnmarshaller(filepath.Ext(filename))([]byte(fileData), v)
}
// loadFileConfig unmarshals the file's content with the right
// decoder format according to the filename extension. If no
// extension is provided, json will be selected by default.