gogo-context

Using built-in types in context.WithValue


Go docs for context.WithValue says not to use built-in types for value keys because of potential collisions between packages using context.

Is that recommendation actually relevant? Can someone point to a real-world scenario when multiple packages may share a context and use same keys to access values?


Solution

  • Here is a simple example. Both packages track whether or not they've started using the key "started". A.Start calls B.Start. B.Start panics because it thinks its already started.

    package main
    
    import "context"
    
    func main() {
      A.Start(context.Background())
    }
    
    package A
    
    import "context"
    
    func Start(ctx context.Context) {
      if ctx.Value("started") == true {
        panic("already started")
      }
      newCtx := context.WithValue(ctx, "started", true)
      B.Start(newCtx)
    }
    
    package B
    
    import "context"
    
    func Start(ctx context.Context) {
      if ctx.Value("started") == true {
        panic("already started")
      }
    }