Back to godoc.org
go.etcd.io/etcd / clientv3 / clientv3util

Package clientv3util

v3.3.22+incompatible
Latest Go to latest

The latest major version is .

Published: May 20, 2020 | License: Apache-2.0 | Module: go.etcd.io/etcd

Overview

Package clientv3util contains utility functions derived from clientv3.

Index

Examples

func KeyExists

func KeyExists(key string) clientv3.Cmp

KeyExists returns a comparison operation that evaluates to true iff the given key exists. It does this by checking if the key `Version` is greater than 0. It is a useful guard in transaction delete operations.

Example (Delete)

Code:

package main

import (
	"context"
	"github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/clientv3/clientv3util"
	"log"
)

func main() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints: []string{"127.0.0.1:2379"},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer cli.Close()
	kvc := clientv3.NewKV(cli)

	// perform a delete only if key already exists
	_, err = kvc.Txn(context.Background()).
		If(clientv3util.KeyExists("purpleidea")).
		Then(clientv3.OpDelete("purpleidea")).
		Commit()
	if err != nil {
		log.Fatal(err)
	}
}
Example (Put)

Code:

package main

import (
	"context"
	"github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/clientv3/clientv3util"
	"log"
)

func main() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints: []string{"127.0.0.1:2379"},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer cli.Close()
	kvc := clientv3.NewKV(cli)

	// perform a put only if key is missing
	// It is useful to do the check atomically to avoid overwriting
	// the existing key which would generate potentially unwanted events,
	// unless of course you wanted to do an overwrite no matter what.
	_, err = kvc.Txn(context.Background()).
		If(clientv3util.KeyMissing("purpleidea")).
		Then(clientv3.OpPut("purpleidea", "hello world")).
		Commit()
	if err != nil {
		log.Fatal(err)
	}
}

func KeyMissing

func KeyMissing(key string) clientv3.Cmp

KeyMissing returns a comparison operation that evaluates to true iff the given key does not exist.

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier