【问题标题】:Errors when passing metadata into context in golang在 golang 中将元数据传递到上下文时出错
【发布时间】:2017-02-16 18:02:25
【问题描述】:

我正在处理具体的处理 GRPC 请求。我正在尝试根据以下代码示例将 GRPC 请求中的元数据传递到上下文中:https://github.com/go-kit/kit/blob/master/auth/jwt/transport.go#L47

(以防万一,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]] 的操作来修复上述错误。但是,我想将地图的所有元素传递给上下文。

关于如何解决此问题的任何建议?

【问题讨论】:

  • 如果一个标头有多个值,你想如何传递这些值?如果要单独添加它们,只需使用 for 循环。

标签: go grpc


【解决方案1】:

我认为你想使用标题名称作为上下文键:

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)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多