You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

84 lines
2.1 KiB

  1. /*
  2. *
  3. * Copyright 2018 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. // Binary server is an example server.
  19. package main
  20. import (
  21. "context"
  22. "flag"
  23. "fmt"
  24. "log"
  25. "net"
  26. "sync"
  27. epb "google.golang.org/genproto/googleapis/rpc/errdetails"
  28. "google.golang.org/grpc"
  29. "google.golang.org/grpc/codes"
  30. pb "google.golang.org/grpc/examples/helloworld/helloworld"
  31. "google.golang.org/grpc/status"
  32. )
  33. var port = flag.Int("port", 50052, "port number")
  34. // server is used to implement helloworld.GreeterServer.
  35. type server struct {
  36. mu sync.Mutex
  37. count map[string]int
  38. }
  39. // SayHello implements helloworld.GreeterServer
  40. func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
  41. s.mu.Lock()
  42. defer s.mu.Unlock()
  43. // Track the number of times the user has been greeted.
  44. s.count[in.Name]++
  45. if s.count[in.Name] > 1 {
  46. st := status.New(codes.ResourceExhausted, "Request limit exceeded.")
  47. ds, err := st.WithDetails(
  48. &epb.QuotaFailure{
  49. Violations: []*epb.QuotaFailure_Violation{{
  50. Subject: fmt.Sprintf("name:%s", in.Name),
  51. Description: "Limit one greeting per person",
  52. }},
  53. },
  54. )
  55. if err != nil {
  56. return nil, st.Err()
  57. }
  58. return nil, ds.Err()
  59. }
  60. return &pb.HelloReply{Message: "Hello " + in.Name}, nil
  61. }
  62. func main() {
  63. flag.Parse()
  64. address := fmt.Sprintf(":%v", *port)
  65. lis, err := net.Listen("tcp", address)
  66. if err != nil {
  67. log.Fatalf("failed to listen: %v", err)
  68. }
  69. s := grpc.NewServer()
  70. pb.RegisterGreeterServer(s, &server{count: make(map[string]int)})
  71. if err := s.Serve(lis); err != nil {
  72. log.Fatalf("failed to serve: %v", err)
  73. }
  74. }