How to Use etcd Client in Go

Use the official `go.etcd.io/etcd/client/v3` package to create a client, configure it with your cluster endpoints and timeout, and then perform operations like Put, Get, or Watch via the returned client object.

Use the official go.etcd.io/etcd/client/v3 package to create a client, configure it with your cluster endpoints and timeout, and then perform operations like Put, Get, or Watch via the returned client object. Always ensure you handle context cancellation and errors properly to avoid goroutine leaks or hanging connections.

Here is a practical example showing how to initialize the client and perform a basic key-value operation:

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

func main() {
	// Configure the client with endpoints and timeout
	cfg := clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	}

	// Create the client
	cli, err := clientv3.New(cfg)
	if err != nil {
		log.Fatal("failed to create client:", err)
	}
	defer cli.Close()

	// Create a context with timeout for the operation
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// Put a key-value pair
	_, err = cli.Put(ctx, "my-key", "my-value")
	if err != nil {
		log.Fatal("failed to put key:", err)
	}

	// Get the value back
	resp, err := cli.Get(ctx, "my-key")
	if err != nil {
		log.Fatal("failed to get key:", err)
	}

	if len(resp.Kvs) > 0 {
		fmt.Printf("Retrieved value: %s\n", string(resp.Kvs[0].Value))
	}
}

For more advanced use cases like watching for changes, use cli.Watch(). This returns a channel that streams events. You must run this in a goroutine and ensure the context is cancelled when you are done to prevent resource leaks.

// Example: Watching a key for changes
ch := cli.Watch(ctx, "my-key")
go func() {
	for wresp := range ch {
		for _, ev := range wresp.Events {
			fmt.Printf("Event: %s, Key: %s, Value: %s\n", 
				ev.Type, string(ev.Kv.Key), string(ev.Kv.Value))
		}
	}
}()

Key best practices include always calling defer cli.Close() to release resources, using context.WithTimeout for every RPC call to prevent indefinite blocking, and handling context.Canceled errors gracefully. If your etcd cluster requires TLS, add TLS: &tls.Config{...} to the clientv3.Config struct. For authentication, use clientv3.Auth methods to login before performing operations.