2 回答

TA貢獻1836條經驗 獲得超5個贊
您可能不喜歡默認映射規則,并且可能希望通過所有 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),
)
要將默認映射規則與您自己的規則一起保留,請編寫:
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/。

TA貢獻2021條經驗 獲得超8個贊
可以將 HTTP 標頭映射到 gRPC 元數據,如此處所述
這應該有效:
// in Client.MiddlewareAuth
r.Header.Set("Grpc-Metadata-My-Data", "...")
// in Server.List
md.Get("grpcgateway-My-Data")
- 2 回答
- 0 關注
- 208 瀏覽
添加回答
舉報