# Use the Go client

> Connect clientv3 with tenant certificates and run transactions and watches.

---

LLMS index: [llms.txt](/llms.txt)

---

This example uses the official `go.etcd.io/etcd/client/v3` package (`v3.7.2` in the `pgetcd` `go.mod`) to connect to a running development tenant over mutual TLS, execute a conditional `Txn` on `/tutorial/go-client`, and watch the next write starting from `Header.Revision + 1`.

Export the `ETCDCTL_*` environment variables from [Use etcdctl](/docs/etcd/tutorial/etcdctl/#connect) before running the program.

## Write the program {#code}

Create `.cache/tutorial-client/main.go` inside the `pgetcd` checkout (`.cache/` is ignored by Git):

```go
package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"os"
	"time"

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

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func run() error {
	if len(os.Args) != 5 {
		return errors.New("usage: client <endpoint> <server-ca> <client-cert> <client-key>")
	}
	ca, err := os.ReadFile(os.Args[2])
	if err != nil {
		return err
	}
	roots := x509.NewCertPool()
	if !roots.AppendCertsFromPEM(ca) {
		return errors.New("invalid server CA")
	}
	cert, err := tls.LoadX509KeyPair(os.Args[3], os.Args[4])
	if err != nil {
		return err
	}
	client, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{os.Args[1]},
		DialTimeout: 5 * time.Second,
		TLS: &tls.Config{
			MinVersion:   tls.VersionTLS12,
			RootCAs:      roots,
			Certificates: []tls.Certificate{cert},
		},
	})
	if err != nil {
		return err
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	const key = "/tutorial/go-client"
	initial, err := client.Txn(ctx).
		If(clientv3.Compare(clientv3.Version(key), "=", 0)).
		Then(clientv3.OpPut(key, "hello")).
		Else(clientv3.OpGet(key)).
		Commit()
	if err != nil {
		return fmt.Errorf("initial transaction: %w", err)
	}
	fmt.Printf("created=%t revision=%d\n", initial.Succeeded, initial.Header.Revision)

	changes := client.Watch(ctx, key, clientv3.WithRev(initial.Header.Revision+1))
	written, err := client.Put(ctx, key, "updated")
	if err != nil {
		return fmt.Errorf("put: %w", err)
	}
	for response := range changes {
		if err := response.Err(); err != nil {
			return fmt.Errorf("watch: %w", err)
		}
		for _, event := range response.Events {
			if event.Kv.ModRevision == written.Header.Revision {
				fmt.Printf("%s %s=%s revision=%d\n",
					event.Type, event.Kv.Key, event.Kv.Value, event.Kv.ModRevision)
				return nil
			}
		}
	}
	if err := ctx.Err(); err != nil {
		return err
	}
	return errors.New("watch closed before the write was observed")
}
```

## Run the program {#run}

From the `pgetcd` repository root, run:

```bash
go run ./.cache/tutorial-client \
  "$ETCDCTL_ENDPOINTS" "$ETCDCTL_CACERT" "$ETCDCTL_CERT" "$ETCDCTL_KEY"
```

Pass a single endpoint URL in `ETCDCTL_ENDPOINTS`. The first run prints `created=true` followed by the `PUT` event for `updated`. Subsequent runs print `created=false` because `Version(key)` is no longer `0`.

Starting the Watch at `initial.Header.Revision + 1` avoids a race between `Watch` registration and `Put`: even if `Put` commits before the Watch stream finishes registering, `pg_etcd` replays retained events from `initial.Header.Revision + 1` onward.

All operations share a 15-second context timeout. If a write times out or returns an unknown outcome, do not blindly replay a non-idempotent write; [inspect the committed state first](/docs/etcd/operations/troubleshooting/#unknown-commit).

## Clean up and production notes {#next}

Delete the tutorial key when done:

```bash
etcdctl del /tutorial/go-client
```

When writing production `clientv3` consumers:

- Persist your consumer's resume revision only after processing all events of a complete revision.
- If a Watch response carries `CompactRevision > 0` (`ErrCompacted`), take a fresh `Get` snapshot and open a new Watch from `Header.Revision + 1`.
- If stream fragmentation is enabled, wait until `More == false` before treating a revision as complete.

For more details on Watch tailing and Lease lifecycles, see [Watch, Lease and history](/docs/etcd/architecture/watch-lease/).

---

Backlinks:

- [Tutorials](/docs/etcd/tutorial/)
- [Use etcdctl](/docs/etcd/tutorial/etcdctl/)
