I am working on specific with handling GRPC requests. I am trying to pass the meta from my GRPC request into the context based on this code sample: https://github.com/go-kit/kit/blob/master/auth/jwt/transport.go#L47.
(just in case, the contextKey explanation can be referred here: https://medium.com/@matryer/context-keys-in-go-5312346a868d#.vn10llkse):
Below is my code:
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
}
}
I am trying to read metadata fields (Headers) and pass it to the context.
I am getting the following errors. cannot use header (type []string) as type string in map index
and cannot convert header (type []string) to type contextKey
. I had fixed the above errors by accessing the index and doing something like this val, ok := (*md)[header[0]]
. However, I want to pass all the elements of the map to the context.
Any suggestions on how to work around this problem?
I think you want to use the header name as the context key:
for name, header := range Headers {
val := r.Header.Get(header)
if len(val) > 0 {
ctx = context.WithValue(ctx, contextKey(name), val)
}
}
Alternatively, store the headers as a single value:
ctx = context.WithValue(ctx, contextKey("headers"), Headers)