trpc.group/trpc-go/trpc-go@v1.0.3/internal/context/value_ctx.go (about)

     1  // Package context provides extensions to context.Context.
     2  package context
     3  
     4  import (
     5  	"context"
     6  )
     7  
     8  // NewContextWithValues will use the valuesCtx's Value function.
     9  // Effects of the returned context:
    10  //
    11  //	Whether it has timed out or canceled: decided by ctx.
    12  //	Retrieve value using key: first use valuesCtx.Value, then ctx.Value.
    13  func NewContextWithValues(ctx, valuesCtx context.Context) context.Context {
    14  	return &valueCtx{Context: ctx, values: valuesCtx}
    15  }
    16  
    17  type valueCtx struct {
    18  	context.Context
    19  	values context.Context
    20  }
    21  
    22  // Value re-implements context.Value, valueCtx.values.Value has the highest
    23  // priority.
    24  func (c *valueCtx) Value(key interface{}) interface{} {
    25  	if v := c.values.Value(key); v != nil {
    26  		return v
    27  	}
    28  	return c.Context.Value(key)
    29  }