example_key_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. package clientv3util_test
  15. import (
  16. "context"
  17. "log"
  18. "go.etcd.io/etcd/clientv3"
  19. "go.etcd.io/etcd/clientv3/clientv3util"
  20. )
  21. func ExampleKeyMissing() {
  22. cli, err := clientv3.New(clientv3.Config{
  23. Endpoints: []string{"127.0.0.1:2379"},
  24. })
  25. if err != nil {
  26. log.Fatal(err)
  27. }
  28. defer cli.Close()
  29. kvc := clientv3.NewKV(cli)
  30. // perform a put only if key is missing
  31. // It is useful to do the check atomically to avoid overwriting
  32. // the existing key which would generate potentially unwanted events,
  33. // unless of course you wanted to do an overwrite no matter what.
  34. _, err = kvc.Txn(context.Background()).
  35. If(clientv3util.KeyMissing("purpleidea")).
  36. Then(clientv3.OpPut("purpleidea", "hello world")).
  37. Commit()
  38. if err != nil {
  39. log.Fatal(err)
  40. }
  41. }
  42. func ExampleKeyExists() {
  43. cli, err := clientv3.New(clientv3.Config{
  44. Endpoints: []string{"127.0.0.1:2379"},
  45. })
  46. if err != nil {
  47. log.Fatal(err)
  48. }
  49. defer cli.Close()
  50. kvc := clientv3.NewKV(cli)
  51. // perform a delete only if key already exists
  52. _, err = kvc.Txn(context.Background()).
  53. If(clientv3util.KeyExists("purpleidea")).
  54. Then(clientv3.OpDelete("purpleidea")).
  55. Commit()
  56. if err != nil {
  57. log.Fatal(err)
  58. }
  59. }