Created
December 3, 2015 06:49
-
-
Save wangkuiyi/72b59f3ac96c384aca02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The official etcd Go client library is far from easy-to-use. I had | |
// to read github.com/coreos/etcd/client and | |
// github.com/coreos/etcd/etcdctl before I can write down the | |
// following sample code which updates a key value. | |
// | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"net/url" | |
"strings" | |
"time" | |
"github.com/coreos/etcd/client" | |
"github.com/coreos/etcd/pkg/transport" | |
"golang.org/x/net/context" | |
) | |
func main() { | |
flagEtcd := flag.String("etcd", "http://127.0.0.1:4001,http://127.0.0.1:2379", "Etcd peers addresses") | |
flag.Parse() | |
eps := strings.Split(*flagEtcd, ",") | |
for i, ep := range eps { | |
u, e := url.Parse(ep) | |
if e != nil { | |
log.Fatal("url.Parse: ", e) | |
} | |
if u.Scheme == "" { | |
u.Scheme = "http" | |
} | |
eps[i] = u.String() | |
} | |
tr, e := transport.NewTransport(transport.TLSInfo{}) | |
if e != nil { | |
log.Fatal("transport.NewTransport: ", e) | |
} | |
etcd, e := client.New(client.Config{ | |
Endpoints: eps, | |
Transport: tr}) | |
if e != nil { | |
log.Fatal("client.New: ", e) | |
} | |
ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout) | |
e = etcd.Sync(ctx) | |
cancel() | |
if e != nil { | |
log.Fatal("etcd.Sync: ", e) | |
} | |
etcdKeys := client.NewKeysAPI(etcd) | |
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(5*time.Second)) | |
resp, e := etcdKeys.Set(ctx, "/a", "Macintosh computer", &client.SetOptions{}) | |
cancel() | |
if e != nil { | |
log.Fatal("etcKeys.Set: ", e) | |
} | |
fmt.Println(resp) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment