繁体   English   中英

如何从 grpc-gateway 发送元数据到 grpc 服务器?

[英]How to send metadata from grpc-gateway to go grpc server?

如何将元数据从 grpc-gateway 发送到 grpc 服务器?

在客户端(grpc-网关)上:

func (c *Client) MiddlewareAuth(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()

        ...

        ctxOut := metadata.NewOutgoingContext(ctx, metadata.New(map[string]string{
            "key":    "value",
        }))

        r = r.WithContext(ctxOut)

        h.ServeHTTP(w, r)
    })
}

在服务器上:

func (s *Server) List(ctx context.Context, request *pb.Request) (*pb.Response, error) {
    md, _ := metadata.FromIncomingContext(ctx)
    fmt.Println(md)

    return &pb.Response{
        Ok: true
    }, nil
}

这是可能的HTTP头映射到GRPC元数据,描述在这里

这应该有效:

// in Client.MiddlewareAuth
r.Header.Set("Grpc-Metadata-My-Data", "...")

// in Server.List
md.Get("grpcgateway-My-Data")

您可能不喜欢默认映射规则,并且可能希望通过所有 HTTP 标头,例如:

  1. 编写一个HeaderMatcherFunc

  2. 使用WithIncomingHeaderMatcher注册函数

例如

func CustomMatcher(key string) (string, bool) {
 switch key {
 case "X-Custom-Header1":
 return key, true
 case "X-Custom-Header2":
 return "custom-header2", true
 default:
 return key, false
 }
}

mux := runtime.NewServeMux(
 runtime.WithIncomingHeaderMatcher(CustomMatcher),
)

要将默认映射规则与您自己的规则一起保留,请编写:

func CustomMatcher(key string) (string, bool) {
 switch key {
 case "X-User-Id":
 return key, true
 default:
 return runtime.DefaultHeaderMatcher(key)
 }
}

它将适用于两者:

$ curl --header "x-user-id: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ...

$ curl --header "X-USER-ID: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ...

要在 gRPC 服务器端访问此标头,请使用:

userID := ""
if md, ok := metadata.FromIncomingContext(ctx); ok {
 if uID, ok := md["x-user-id"]; ok {
 userID = strings.Join(uID, ",")
 }
}

此外,您应该查看关于 gRPC-Gateway 的系列教程,即https://grpc-ecosystem.github.io/grpc-gateway/docs/tutorials/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM