example_key_test.go 1.8 KB

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