在使用 gRPC-gateway 时,可以通过 HTTP 请求头将数据传递到 gRPC 元数据中。具体步骤如下:
定义一个 HTTP 请求头,用于传递需要的数据。
在 gRPC service 中定义一个 context.Context 参数,用于接收元数据。
在 gRPC-gateway 的转发器中获取该请求头,并将其转换为 gRPC 元数据传递给服务端。
例如,在以下的 proto 文件中定义了一个名为 X-Request-Id 的 HTTP 请求头:
syntax = "proto3";
package example;
import "google/api/annotations.proto";
import "google/protobuf/empty.proto";
service MyService {
rpc MyMethod (google.protobuf.Empty) returns (google.protobuf.Empty) {
option (google.api.http) = {
post: "/my/method"
body: "*"
additional_bindings {
post: "/v1/my/method"
body: "*"
headers {
key: "X-Request-Id"
value: "{x_request_id}"
}
}
};
}
}
然后,在实现服务端的方法时,可以添加一个 context.Context 参数来接收该请求头:
func (s *myServiceServer) MyMethod(ctx context.Context, req *empty.Empty) (*empty.Empty, error) {
requestID := metadata.Get(ctx, "x-request-id")
// 处理业务逻辑...
}
最后,在转发器中获取该请求头并将其转换为 gRPC 元数据:
mux := runtime.NewServeMux(
runtime.WithIncomingHeaderMatcher(func(header string) (string, bool) {
if header == "X-Request-Id" {
return metadata.HeaderMDKey(header), true
}
return runtime.DefaultHeaderMatcher(header)
}),
)
metadata := metadata.Pairs("x-request-id", requestID)
ctx := metadata.NewOutgoingContext(context.Background(), metadata)
resp, err := client.MyMethod(ctx, req)




