Created
February 15, 2022 16:23
-
-
Save romanitalian/a1d303b837bee849e443670ad1522b27 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
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