1. proto

  1. syntax = "proto3";
  2. option go_package = ".;proto";
  3. service Greeter {
  4. rpc SayHello (HelloRequest) returns (HelloReply);
  5. }
  6. //将 sessionid放入 放入cookie中 http协议
  7. message HelloRequest {
  8. string name = 1;
  9. }
  10. message HelloReply {
  11. string message = 1;
  12. }

2. 客户端

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "google.golang.org/grpc"
  6. "time"
  7. "start/grpc_interceptor/proto"
  8. )
  9. func interceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  10. start := time.Now()
  11. err := invoker(ctx, method, req, reply, cc, opts...)
  12. fmt.Printf("method=%s req=%v rep=%v duration=%s error=%v\n", method, req, reply, time.Since(start), err)
  13. return err
  14. }
  15. func main(){
  16. //stream
  17. var opts []grpc.DialOption
  18. opts = append(opts, grpc.WithInsecure())
  19. // 指定客户端interceptor
  20. opts = append(opts, grpc.WithUnaryInterceptor(interceptor))
  21. conn, err := grpc.Dial("localhost:50051", opts...)
  22. if err != nil {
  23. panic(err)
  24. }
  25. defer conn.Close()
  26. c := proto.NewGreeterClient(conn)
  27. r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name:"bobby"})
  28. if err != nil {
  29. panic(err)
  30. }
  31. fmt.Println(r.Message)
  32. }

3. 服务端

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "google.golang.org/grpc"
  7. "start/grpc_interceptor/proto"
  8. )
  9. type Server struct{}
  10. func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply,
  11. error){
  12. return &proto.HelloReply{
  13. Message: "hello "+request.Name,
  14. }, nil
  15. }
  16. func main(){
  17. var interceptor grpc.UnaryServerInterceptor
  18. interceptor = func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
  19. // 继续处理请求
  20. fmt.Println("接收到新请求")
  21. res, err := handler(ctx, req)
  22. fmt.Println("请求处理完成")
  23. return res, err
  24. }
  25. var opts []grpc.ServerOption
  26. opts = append(opts, grpc.UnaryInterceptor(interceptor))
  27. g := grpc.NewServer(opts...)
  28. proto.RegisterGreeterServer(g, &Server{})
  29. lis, err := net.Listen("tcp", "0.0.0.0:50051")
  30. if err != nil{
  31. panic("failed to listen:"+err.Error())
  32. }
  33. err = g.Serve(lis)
  34. if err != nil{
  35. panic("failed to start grpc:"+err.Error())
  36. }
  37. }

4. 拦截器的应用场景

go-grpc-middleware