example_keys_test.go 2.2 KB

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