Skip to content

Instantly share code, notes, and snippets.

@developer-guy
Created April 20, 2021 20:03
Show Gist options
  • Save developer-guy/3dad786ad1ea334936f769d4c4537ae4 to your computer and use it in GitHub Desktop.
Save developer-guy/3dad786ad1ea334936f769d4c4537ae4 to your computer and use it in GitHub Desktop.
Working with etcd through Go client
package main
import (
"context"
"crypto/tls"
"time"
"github.com/sirupsen/logrus"
v3 "go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/pkg/transport"
)
func main() {
tlsinfo := transport.TLSInfo{}
tlsinfo.CertFile = "./etcd/server.crt"
tlsinfo.KeyFile = "./etcd/server.key"
tlsinfo.TrustedCAFile = "./etcd/ca.crt"
var tlsConf *tls.Config
if !tlsinfo.Empty() {
tlsConf, _ = tlsinfo.ClientConfig()
}
etcdClient, err := v3.New(v3.Config{
Endpoints: []string{"127.0.0.1:2379"},
DialTimeout: time.Minute,
AutoSyncInterval: time.Minute,
TLS: tlsConf,
})
if err != nil {
logrus.WithError(err).Fatal("Failed to new etcd client")
}
todoCtx := context.TODO()
defaultOpts := []v3.OpOption{v3.WithPrefix(), v3.WithKeysOnly(), v3.WithSerializable()}
ctx, cancel := context.WithTimeout(todoCtx, 5*time.Second)
defer cancel()
resp, err := etcdClient.Get(ctx, "/", defaultOpts...)
if err != nil {
logrus.WithError(err).Fatal("Failed to Get keys with prefix \\")
}
for _, kv := range resp.Kvs {
logrus.Infof("Key: %s", string(kv.Key))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment