2017-02-16 50 views
0

我正在與處理特定問題,處理GRPC請求。我試圖從我的GRPC請求中將meta傳遞到基於此代碼示例的上下文中:https://github.com/go-kit/kit/blob/master/auth/jwt/transport.go#L47golang將元數據傳遞到上下文時的錯誤

(以防萬一,在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 indexcannot convert header (type []string) to type contextKey。我通過訪問索引並執行類似val, ok := (*md)[header[0]]的操作來解決上述錯誤。但是,我想將地圖的所有元素傳遞給上下文。

有關如何解決此問題的任何建議?

+0

如果頭部有多個值,怎麼辦你想通過這些?如果你想單獨添加它們,只需使用for循環。 – JimB

回答

2

我想你想使用的頭名的情況下鍵:

for name, header := range Headers { 
    val := r.Header.Get(header) 
    if len(val) > 0 { 
    ctx = context.WithValue(ctx, contextKey(name), val) 
    } 
} 

另外,標題存儲爲單個值:

ctx = context.WithValue(ctx, contextKey("headers"), Headers) 
+0

CeriseLimon:你有任何建議閱讀GRPC請求的元數據基於這個:https://github.com/go-kit/kit/blob/master/auth/jwt/transport.go#L47? – Sanket

相關問題