Golang context.WithValue: how to add several key-value pairs

后端 未结 5 1062
一生所求
一生所求 2020-12-24 11:24

With Go\'s context package it is possible to pass request-specific data to the stack of request handling functions using

func WithValue(parent C         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 12:08

    One (functional) way to do it is using currying and closures

    r.WithContext(BuildContext(
       r.Context(),
       SchemaId(mySchemaId),
       RequestId(myRequestId),
       Logger(myLogger)
    ))
    
    func RequestId(id string) partialContextFn {
       return func(ctx context.Context) context.Context {
          return context.WithValue(ctx, requestIdCtxKey, requestId)
       }
    }
    
    func BuildContext(ctx context.Context, ctxFns ...partialContextFn) context.Context {
       for f := range ctxFns {
          ctx = f(ctx)
       }
    
       return ctx
    } 
    
    type partialContextFn func(context.Context) context.Context
    

提交回复
热议问题