我正在與處理特定問題,處理GRPC請求。我試圖從我的GRPC請求中將meta傳遞到基於此代碼示例的上下文中:https://github.com/go-kit/kit/blob/master/auth/jwt/transport.go#L47。golang將元數據傳遞到上下文時的錯誤
(以防萬一,在contextKey解釋在這裏簡稱:https://medium.com/@matryer/context-keys-in-go-5312346a868d#.vn10llkse):
下面是我的代碼:
type contextKey string
func (c contextKey) String() string {
return string(c)
}
var Headers := metadata.New(map[string]string{"auth":"", "abc": "", "xyz" : ""})
func ToGRPCContext() grpctransport.RequestFunc {
return func(ctx context.Context, md *metadata.MD) context.Context {
for _, header := range Headers {
val, ok := (*md)[header]
if !ok {
return ctx
}
if len(val) > 0 {
ctx = context.WithValue(ctx, contextKey(header), val)
}
}
return ctx
}
}
我想讀的元數據字段(頭),並把它傳遞給上下文。
我收到以下錯誤。 cannot use header (type []string) as type string in map index
和cannot convert header (type []string) to type contextKey
。我通過訪問索引並執行類似val, ok := (*md)[header[0]]
的操作來解決上述錯誤。但是,我想將地圖的所有元素傳遞給上下文。
有關如何解決此問題的任何建議?
如果頭部有多個值,怎麼辦你想通過這些?如果你想單獨添加它們,只需使用for循環。 – JimB