WithValue
- Go course
- Intermediate
- Lesson 32/80
- 4 min
Learn to carry values inside a context with WithValue.
WithValue
context.WithValue(parent, key, value) carries request-scoped data (request ID, user, trace info). The key should be a private unexported type so it doesn't collide with other packages:
type anahtar int
const userKey anahtar = 0
ctx = context.WithValue(ctx, userKey, "ada")
ad, ok := ctx.Value(userKey).(string)Type-safe helpers
A common pattern is to hide the key inside the package and export only helper functions:
func WithUser(ctx context.Context, ad string) context.Context {
return context.WithValue(ctx, userKey, ad)
}
func User(ctx context.Context) (string, bool) {
ad, ok := ctx.Value(userKey).(string)
return ad, ok
}Callers then don't deal with type assertions and the key can't be changed from outside.
Practice Carry the user
Define type ctxKey struct{}. Write the WithUser and User helpers. Add the user "ada", read it back and print the value and ok.
Starter code
package main
import (
"context"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"context"
"fmt"
)
type ctxKey struct{}
func WithUser(ctx context.Context, ad string) context.Context {
return context.WithValue(ctx, ctxKey{}, ad)
}
func User(ctx context.Context) (string, bool) {
ad, ok := ctx.Value(ctxKey{}).(string)
return ad, ok
}
func main() {
ctx := WithUser(context.Background(), "ada")
fmt.Println(User(ctx))
}Expected output
ada true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is <strong>not</strong> suitable for WithValue?
- A request ID
- The authenticated user
- Trace information
- A function's required parameters (e.g. a database connection) Correct answer
Explanation: Required dependencies should be explicit parameters; hiding them in the context makes code unclear and type-unsafe.
2 Read the value
id, ok := ctx.____(istekKey).(string)
id, ok := ctx.Value(istekKey).(string)
Explanation: ctx.Value returns the value for the key as any; a type assertion converts it.
3 Usage
| Term | Meaning |
|---|---|
Request ID |
WithValue fits |
Database connection |
Explicit parameter |
Private key type |
Prevents collisions |
Helper function |
Type-safe access |