example_keys_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 client_test
  15. import (
  16. "context"
  17. "fmt"
  18. "log"
  19. "sort"
  20. "github.com/coreos/etcd/client"
  21. )
  22. func ExampleKeysAPI_directory() {
  23. c, err := client.New(client.Config{
  24. Endpoints: exampleEndpoints,
  25. Transport: exampleTransport,
  26. })
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. kapi := client.NewKeysAPI(c)
  31. // Setting '/myNodes' to create a directory that will hold some keys.
  32. o := client.SetOptions{Dir: true}
  33. resp, err := kapi.Set(context.Background(), "/myNodes", "", &o)
  34. if err != nil {
  35. log.Fatal(err)
  36. }
  37. // Add keys to /myNodes directory.
  38. resp, err = kapi.Set(context.Background(), "/myNodes/key1", "value1", nil)
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. resp, err = kapi.Set(context.Background(), "/myNodes/key2", "value2", nil)
  43. if err != nil {
  44. log.Fatal(err)
  45. }
  46. // fetch directory
  47. resp, err = kapi.Get(context.Background(), "/myNodes", nil)
  48. if err != nil {
  49. log.Fatal(err)
  50. }
  51. // print directory keys
  52. sort.Sort(resp.Node.Nodes)
  53. for _, n := range resp.Node.Nodes {
  54. fmt.Printf("Key: %q, Value: %q\n", n.Key, n.Value)
  55. }
  56. // Output:
  57. // Key: "/myNodes/key1", Value: "value1"
  58. // Key: "/myNodes/key2", Value: "value2"
  59. }
  60. func ExampleKeysAPI_setget() {
  61. c, err := client.New(client.Config{
  62. Endpoints: exampleEndpoints,
  63. Transport: exampleTransport,
  64. })
  65. if err != nil {
  66. log.Fatal(err)
  67. }
  68. kapi := client.NewKeysAPI(c)
  69. // Set key "/foo" to value "bar".
  70. resp, err := kapi.Set(context.Background(), "/foo", "bar", nil)
  71. if err != nil {
  72. log.Fatal(err)
  73. }
  74. // Get key "/foo"
  75. resp, err = kapi.Get(context.Background(), "/foo", nil)
  76. if err != nil {
  77. log.Fatal(err)
  78. }
  79. fmt.Printf("%q key has %q value\n", resp.Node.Key, resp.Node.Value)
  80. // Output: "/foo" key has "bar" value
  81. }