main.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. *
  3. * Copyright 2015 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package main implements a client for Greeter service.
  19. package main
  20. import (
  21. "context"
  22. "log"
  23. "os"
  24. "time"
  25. "google.golang.org/grpc"
  26. pb "google.golang.org/grpc/examples/helloworld/helloworld"
  27. )
  28. const (
  29. address = "localhost:50051"
  30. defaultName = "world"
  31. )
  32. func main() {
  33. // Set up a connection to the server.
  34. conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
  35. if err != nil {
  36. log.Fatalf("did not connect: %v", err)
  37. }
  38. defer conn.Close()
  39. c := pb.NewGreeterClient(conn)
  40. // Contact the server and print out its response.
  41. name := defaultName
  42. if len(os.Args) > 1 {
  43. name = os.Args[1]
  44. }
  45. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  46. defer cancel()
  47. r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
  48. if err != nil {
  49. log.Fatalf("could not greet: %v", err)
  50. }
  51. log.Printf("Greeting: %s", r.GetMessage())
  52. }