亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將元數據從 grpc-gateway 發送到 grpc 服務器?

如何將元數據從 grpc-gateway 發送到 grpc 服務器?

Go
HUH函數 2022-04-26 10:34:38
如何將元數據從 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}
查看完整描述

2 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

您可能不喜歡默認映射規則,并且可能希望通過所有 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-Gateway 的教程系列,即https://grpc-ecosystem.github.io/grpc-gateway/docs/tutorials/。


查看完整回答
反對 回復 2022-04-26
?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

可以將 HTTP 標頭映射到 gRPC 元數據,如此處所述


這應該有效:


// in Client.MiddlewareAuth

r.Header.Set("Grpc-Metadata-My-Data", "...")


// in Server.List

md.Get("grpcgateway-My-Data")


查看完整回答
反對 回復 2022-04-26
  • 2 回答
  • 0 關注
  • 208 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號