Go Context Values: Custom Key Collisions
In this tutorial, you'll learn about Go Context Values: Custom Key Collisions. We cover key concepts, practical examples, and best practices.
Context value keys -- Prevent key collisions by using unexported custom types instead of strings for context values.
The Problem
Using string keys for context.WithValue can collide with other packages using the same key string. Always define an unexported type for your keys.
Wrong
ctx := context.WithValue(ctx, "user_id", 42)
val := ctx.Value("user_id") // OK but collision-prone
Output:
// Another package might also use "user_id" key
Right
type contextKey string
const userIDKey contextKey = "user_id"
ctx := context.WithValue(ctx, userIDKey, 42)
val := ctx.Value(userIDKey).(int)
Output:
// Type-safe, collision-free key
Prevention
- Define unexported types for context keys
- Use typed constants, not raw strings
- Use helper functions to get/set values
- Context values should be request-scoped only
- Do not use context to pass optional parameters
Common Mistakes with context value key
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro