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

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


在客户端(grpc-gateway)上:


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

}


HUH函数
浏览 177回答 2
2回答

一只甜甜圈

您可能不喜欢默认映射规则,并且可能希望通过所有 HTTP 标头,例如:写一个HeaderMatcherFunc。注册函数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/。

宝慕林4294392

可以将 HTTP 标头映射到 gRPC 元数据,如此处所述这应该有效:// in Client.MiddlewareAuthr.Header.Set("Grpc-Metadata-My-Data", "...")// in Server.Listmd.Get("grpcgateway-My-Data")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go