example_kv_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2016 CoreOS, Inc.
  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 clientv3_test
  15. import (
  16. "fmt"
  17. "log"
  18. "time"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  20. "github.com/coreos/etcd/clientv3"
  21. )
  22. func ExampleKV_put() {
  23. var (
  24. dialTimeout = 5 * time.Second
  25. requestTimeout = 1 * time.Second
  26. )
  27. cli, err := clientv3.New(clientv3.Config{
  28. Endpoints: []string{"localhost:12378", "localhost:22378", "localhost:32378"},
  29. DialTimeout: dialTimeout,
  30. })
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34. defer cli.Close()
  35. kvc := clientv3.NewKV(cli)
  36. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  37. resp, err := kvc.Put(ctx, "sample_key", "sample_value")
  38. cancel()
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. fmt.Println("OK")
  43. fmt.Println(resp.Header)
  44. }
  45. func ExampleKV_get() {
  46. var (
  47. dialTimeout = 5 * time.Second
  48. requestTimeout = 1 * time.Second
  49. )
  50. cli, err := clientv3.New(clientv3.Config{
  51. Endpoints: []string{"localhost:12378", "localhost:22378", "localhost:32378"},
  52. DialTimeout: dialTimeout,
  53. })
  54. if err != nil {
  55. log.Fatal(err)
  56. }
  57. defer cli.Close()
  58. kvc := clientv3.NewKV(cli)
  59. ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  60. resp, err := kvc.Get(ctx, "sample_key")
  61. cancel()
  62. if err != nil {
  63. log.Fatal(err)
  64. }
  65. fmt.Println("OK")
  66. for _, ev := range resp.Kvs {
  67. fmt.Printf("%s : %s\n", ev.Key, ev.Value)
  68. }
  69. }