如何将元数据从 grpc 网关发送到 grpc 服务器?



如何将元数据从 grpc 网关发送到 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
}

您可能不喜欢默认映射规则,并且可能希望传递所有 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 网关的教程系列,即 https://grpc-ecosystem.github.io/grpc-gateway/docs/tutorials/。

可以将 HTTP 标头映射到 gRPC 元数据,如此处所述

这应该有效:

// in Client.MiddlewareAuth
r.Header.Set("Grpc-Metadata-My-Data", "...")
// in Server.List
md.Get("grpcgateway-My-Data")

最新更新