Context and Cancellation
Helper Context
Passing context into a helper lets the helper read request-scoped data.
Helper Context
helper_context.go
package main
import (
"context"
"fmt"
)
type requestKey string
func labelRequest(ctx context.Context, action string) string {
id := ctx.Value(requestKey("id"))
return fmt.Sprintf("%v:%s", id, action)
}
func main() {
var action =
ctx := context.WithValue(context.Background(), requestKey("id"), "req-7")
label := labelRequest(ctx, action)
fmt.Println("action=", action)
fmt.Println("label=", label)
}
package main
import (
"context"
"fmt"
)
type requestKey string
func labelRequest(ctx context.Context, action string) string {
id := ctx.Value(requestKey("id"))
return fmt.Sprintf("%v:%s", id, action)
}
func main() {
var action =
ctx := context.WithValue(context.Background(), requestKey("id"), "req-7")
label := labelRequest(ctx, action)
fmt.Println("action=", action)
fmt.Println("label=", label)
}
package main
import (
"context"
"fmt"
)
type requestKey string
func labelRequest(ctx context.Context, action string) string {
id := ctx.Value(requestKey("id"))
return fmt.Sprintf("%v:%s", id, action)
}
func main() {
var action =
ctx := context.WithValue(context.Background(), requestKey("id"), "req-7")
label := labelRequest(ctx, action)
fmt.Println("action=", action)
fmt.Println("label=", label)
}
pass context
Functions usually accept a context as their first parameter so callers can pass values and cancellation.