Sobes.tech
Middle+

For what scenarios can you use context.WithValue?

sobes.tech AI

Answer from AI

context.WithValue in Go is used to pass values associated with the execution context through a chain of calls, typically for passing metadata such as request identifiers, authentication tokens, timeouts, etc.

Use cases:

  • Passing request-related information, such as user or session ID, without changing function signatures.
  • Passing data needed at middleware or logging levels.
  • Storing parameters in the context that should be accessible deep within the call stack.

It is important to remember that context.WithValue is not intended for passing large data or business logic, but only small values related to the context.

Example:

ctx := context.Background()
ctx = context.WithValue(ctx, "requestID", "12345")

func handler(ctx context.Context) {
    if reqID, ok := ctx.Value("requestID").(string); ok {
        fmt.Println("Request ID:", reqID)
    }
}

handler(ctx)
For what scenarios can you use context.WithValue… - sobes.tech