如何从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
}发布于 2020-02-21 16:53:55
可以将HTTP头映射到gRPC元数据,如here所述
这应该是可行的:
// in Client.MiddlewareAuth
r.Header.Set("Grpc-Metadata-My-Data", "...")
// in Server.List
md.Get("grpcgateway-My-Data")发布于 2021-05-01 18:32:44
您可能不喜欢the default mapping rule,并且可能希望传递所有的HTTP头,例如:
例如:
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),
)要将the default mapping rule与您自己的规则放在一起,请编写:
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/。
https://stackoverflow.com/questions/59305337
复制相似问题