1.proto

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

2.server

  1. package main
  2. import (
  3. "OldPackageTest/grpc_test/proto"
  4. "context"
  5. "fmt"
  6. "google.golang.org/grpc"
  7. "google.golang.org/grpc/codes"
  8. "google.golang.org/grpc/metadata"
  9. "google.golang.org/grpc/status"
  10. "net"
  11. )
  12. type Server struct {
  13. }
  14. func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply, error) {
  15. return &proto.HelloReply{
  16. Message: "hello " + request.Name,
  17. }, nil
  18. }
  19. func main() {
  20. interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
  21. fmt.Println("接收到了一个新的请求")
  22. md, ok := metadata.FromIncomingContext(ctx)
  23. fmt.Println(md)
  24. if !ok {
  25. //已经开始接触到grpc的错误处理了
  26. return resp, status.Error(codes.Unauthenticated, "无token认证信息")
  27. }
  28. var (
  29. appid string
  30. appkey string
  31. )
  32. if va1, ok := md["appid"]; ok {
  33. appid = va1[0]
  34. }
  35. if va1, ok := md["appkey"]; ok {
  36. appkey = va1[0]
  37. }
  38. if appid != "101010" || appkey != "I am key" {
  39. return resp, status.Error(codes.Unauthenticated, "无token认证信息")
  40. }
  41. res, err := handler(ctx, req)
  42. fmt.Println("请求已经完成")
  43. return res, err
  44. }
  45. opt := grpc.UnaryInterceptor(interceptor)
  46. g := grpc.NewServer(opt)
  47. proto.RegisterGreeterServer(g, &Server{})
  48. lis, err := net.Listen("tcp", "0.0.0.0:8080")
  49. if err != nil {
  50. panic("failed to listen" + err.Error())
  51. }
  52. err = g.Serve(lis)
  53. if err != nil {
  54. panic("failed to start" + err.Error())
  55. }
  56. }

3.client

  1. package main
  2. import (
  3. "OldPackageTest/grpc_test/proto"
  4. "context"
  5. "fmt"
  6. "google.golang.org/grpc"
  7. )
  8. type customCredential struct {
  9. }
  10. func (c customCredential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  11. return map[string]string{
  12. "appid": "101010",
  13. "appkey": "I am key",
  14. },nil
  15. }
  16. func (c customCredential) RequireTransportSecurity() bool {
  17. return false
  18. }
  19. func main() {
  20. //stream
  21. //interceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error{
  22. // start := time.Now()
  23. // md :=metadata.New(map[string]string{
  24. // "appid":"101010",
  25. // "appkey":"I am key",
  26. // })
  27. // ctx = metadata.NewOutgoingContext(context.Background(), md)
  28. // err := invoker(ctx, method, req, reply, cc, opts...)
  29. // if err != nil {
  30. // return err
  31. // }
  32. // fmt.Printf("耗时: %s\n",time.Since(start))
  33. // return err
  34. //}
  35. grpc.WithPerRPCCredentials(customCredential{})
  36. var opts []grpc.DialOption
  37. opts = append(opts, grpc.WithInsecure())
  38. opts = append(opts, grpc.WithPerRPCCredentials(customCredential{}))
  39. //opt := grpc.WithUnaryInterceptor(interceptor)
  40. //conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure(),opt)
  41. conn, err := grpc.Dial("127.0.0.1:8080", opts...)
  42. if err != nil {
  43. panic(err)
  44. }
  45. defer conn.Close()
  46. c := proto.NewGreeterClient(conn)
  47. r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "Anwma"})
  48. if err != nil {
  49. panic(err)
  50. }
  51. fmt.Println(r.Message)
  52. }