import ( "fmt" "time" "github.com/coreos/etcd/client" ) func main() { cfg := client.Config{ Endpoints: []string{"http://localhost:2379"}, } cli, err := client.New(cfg) if err != nil { panic(err) } kapi := client.NewKeysAPI(cli) watch := kapi.Watcher("/my/key", &client.WatcherOptions{Recursive: false}) for { resp, err := watch.Next(context.Background()) if err != nil { panic(err) } fmt.Printf("Key changed: %s\n", resp.Node.Key) fmt.Printf("New value: %s\n", resp.Node.Value) } }
import ( "fmt" "time" "github.com/coreos/etcd/client" ) func main() { cfg := client.Config{ Endpoints: []string{"http://localhost:2379"}, } cli, err := client.New(cfg) if err != nil { panic(err) } kapi := client.NewKeysAPI(cli) watch := kapi.Watcher("/my/directory", &client.WatcherOptions{Recursive: true}) for { resp, err := watch.Next(context.Background()) if err != nil { panic(err) } if resp.Node.Dir { fmt.Printf("Directory changed: %s\n", resp.Node.Key) } else { fmt.Printf("Key changed: %s\n", resp.Node.Key) fmt.Printf("New value: %s\n", resp.Node.Value) } } }This example watches for changes to the directory "/my/directory" in etcd. Whenever a key in the directory changes, the program will print out the new value of the key. If a new key is added or deleted from the directory, the program will print out the key name with "Directory changed" message.