go.etcd.io/etcd@v3.3.27+incompatible/clientv3/clientv3util/example_key_test.go (about)

     1  // Copyright 2017 The etcd Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package clientv3util_test
    16  
    17  import (
    18  	"context"
    19  	"log"
    20  
    21  	"github.com/coreos/etcd/clientv3"
    22  	"github.com/coreos/etcd/clientv3/clientv3util"
    23  )
    24  
    25  func ExampleKeyExists_put() {
    26  	cli, err := clientv3.New(clientv3.Config{
    27  		Endpoints: []string{"127.0.0.1:2379"},
    28  	})
    29  	if err != nil {
    30  		log.Fatal(err)
    31  	}
    32  	defer cli.Close()
    33  	kvc := clientv3.NewKV(cli)
    34  
    35  	// perform a put only if key is missing
    36  	// It is useful to do the check atomically to avoid overwriting
    37  	// the existing key which would generate potentially unwanted events,
    38  	// unless of course you wanted to do an overwrite no matter what.
    39  	_, err = kvc.Txn(context.Background()).
    40  		If(clientv3util.KeyMissing("purpleidea")).
    41  		Then(clientv3.OpPut("purpleidea", "hello world")).
    42  		Commit()
    43  	if err != nil {
    44  		log.Fatal(err)
    45  	}
    46  }
    47  
    48  func ExampleKeyExists_delete() {
    49  	cli, err := clientv3.New(clientv3.Config{
    50  		Endpoints: []string{"127.0.0.1:2379"},
    51  	})
    52  	if err != nil {
    53  		log.Fatal(err)
    54  	}
    55  	defer cli.Close()
    56  	kvc := clientv3.NewKV(cli)
    57  
    58  	// perform a delete only if key already exists
    59  	_, err = kvc.Txn(context.Background()).
    60  		If(clientv3util.KeyExists("purpleidea")).
    61  		Then(clientv3.OpDelete("purpleidea")).
    62  		Commit()
    63  	if err != nil {
    64  		log.Fatal(err)
    65  	}
    66  }