Junior — Middle
What are the recommended approaches and practices when working with the context and the method context.WithValue?
sobes.tech AI
Answer from AI
When working with context in Go and using context.WithValue, it is important to remember the following recommendations:
- The context is intended for passing cancellation signals, deadlines, and limited request-related information.
- Use
context.WithValueonly for passing data that is needed throughout the request lifecycle and is not suitable for explicit function parameters. - Keys for
WithValueshould be unique and of unexported types to avoid conflicts. Usually, a custom key type is created. - Do not store large objects or data in the context that could lead to memory leaks.
Example of using a key:
package main
import (
"context"
"fmt"
)
type ctxKey string
func main() {
key := ctxKey("userID")
ctx := context.WithValue(context.Background(), key, 42)
userID := ctx.Value(key).(int)
fmt.Println("User ID from context:", userID)
}
Thus, the context is used for passing metadata and managing the lifecycle of operations, not for storing application state.