Skip to content

Instantly share code, notes, and snippets.

@romanitalian
Created February 15, 2022 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romanitalian/a1d303b837bee849e443670ad1522b27 to your computer and use it in GitHub Desktop.
Save romanitalian/a1d303b837bee849e443670ad1522b27 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
clientv3 "go.etcd.io/etcd/client/v3"
)
func NewEtcdClient() (*clientv3.Client, error) {
cl, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
return nil, fmt.Errorf("new etcd client err: %w", err)
}
return cl, nil
}
func EtcdHelloWorld() {
ctx := context.Background()
// step: 0 - connect.
cl, err := NewEtcdClient()
if err != nil {
log.Fatal(err)
}
defer func() {
if er := cl.Close(); er != nil {
log.Fatal(er)
}
}()
// step: 1 - write.
_, err = cl.Put(ctx, "name2", "etcd is great")
if err != nil {
log.Fatal(err)
}
// step: 2 - read.
res, er := cl.Get(ctx, "name2")
if er != nil {
log.Fatal(er)
}
fmt.Printf("res.Kvs[0].Version: %+v\n", res.Kvs[0].Version)
fmt.Printf("res.Kvs[0].Value: %+s\n", res.Kvs[0].Value)
}
func main() {
EtcdHelloWorld()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment