put_command.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2015 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 command
  15. import (
  16. "fmt"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  20. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  21. )
  22. // NewPutCommand returns the cobra command for "put".
  23. func NewPutCommand() *cobra.Command {
  24. return &cobra.Command{
  25. Use: "put",
  26. Short: "Put puts the given key into the store.",
  27. Run: putCommandFunc,
  28. }
  29. }
  30. // putCommandFunc executes the "put" command.
  31. func putCommandFunc(cmd *cobra.Command, args []string) {
  32. if len(args) != 2 {
  33. ExitWithError(ExitBadArgs, fmt.Errorf("put command needs 2 arguments."))
  34. }
  35. key := []byte(args[0])
  36. value := []byte(args[1])
  37. endpoint, err := cmd.Flags().GetString("endpoint")
  38. if err != nil {
  39. ExitWithError(ExitError, err)
  40. }
  41. conn, err := grpc.Dial(endpoint)
  42. if err != nil {
  43. ExitWithError(ExitBadConnection, err)
  44. }
  45. kv := pb.NewKVClient(conn)
  46. req := &pb.PutRequest{Key: key, Value: value}
  47. kv.Put(context.Background(), req)
  48. fmt.Printf("%s %s\n", key, value)
  49. }