0Pricing
Go Academy · Lesson

WithDeadline and WithValue

Absolute deadlines and passing request-scoped values

WithDeadline and WithValue is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

context.WithDeadline

WithDeadline creates a context that cancels at an absolute time. If the parent already has an earlier deadline, the parent deadline takes precedence.

deadline := time.Now().Add(10 * time.Second)
ctx, cancel := context.WithDeadline(parent, deadline)
defer cancel()

WithTimeout vs WithDeadline

WithTimeout(parent, d) is equivalent to WithDeadline(parent, time.Now().Add(d)). Use WithDeadline when you have an absolute expiration (e.g., from an incoming RPC header).

Reading the deadline

Inspect the deadline of any context with ctx.Deadline(). The boolean indicates whether a deadline exists.

if deadline, ok := ctx.Deadline(); ok {
    fmt.Println("expires at:", deadline)
}

context.WithValue

WithValue attaches a key-value pair to the context. Downstream code retrieves it with ctx.Value(key).

type ctxKey string
const userKey ctxKey = "user"

ctx := context.WithValue(parent, userKey, currentUser)

func getUser(ctx context.Context) *User {
    u, _ := ctx.Value(userKey).(*User)
    return u
}

Key collision prevention

Use an unexported package-specific type for keys to prevent collisions between packages. Never use built-in types (string, int) as context keys directly.

// Bad: string key can collide
ctx = context.WithValue(ctx, "user", u)
// Good: package-scoped type
type userKeyType struct{}
ctx = context.WithValue(ctx, userKeyType{}, u)

What to store in context

Only store request-scoped values that cross API boundaries: trace IDs, auth tokens, request IDs. Do not store optional function arguments or mutable state.

WithValue performance

ctx.Value performs a linear search up the context chain. Avoid storing many values per context; for multiple values, group them in a single struct.

type RequestMeta struct {
    UserID  int
    TraceID string
}
type metaKey struct{}
ctx = context.WithValue(ctx, metaKey{}, RequestMeta{...})

Propagating values through middleware

HTTP middleware is the canonical place to attach request metadata to context and retrieve it in handlers:

func Auth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        user := authenticate(r)
        ctx := context.WithValue(r.Context(), userKey, user)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

r.WithContext

Replace an HTTP request's context using r.WithContext(ctx). This creates a shallow copy of the request with the new context, leaving the original unmodified.

Deadline propagation

When a gateway sets a deadline in the context and passes the request downstream, all services that accept the context automatically respect the deadline without explicit timeout logic.

Chain of contexts

Each WithValue, WithCancel, WithTimeout wraps the parent context in a new node. ctx.Value walks the chain until it finds the key or reaches a root context that returns nil.

Quick Check

Why should context keys be unexported package-specific types?

Recap: WithDeadline and WithValue

Key points:

  • WithDeadline cancels at an absolute time; WithTimeout is relative
  • ctx.Deadline() reads the deadline
  • WithValue for request-scoped metadata; use typed unexported keys
  • Group multiple values in a struct to reduce chain depth

Frequently asked questions

Is the “WithDeadline and WithValue” lesson free?

Yes — the full text of “WithDeadline and WithValue” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “WithDeadline and WithValue”?

Absolute deadlines and passing request-scoped values You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “WithDeadline and WithValue” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Why context.Context Exists
  2. WithCancel and WithTimeout
  3. WithDeadline and WithValue
  4. Context in HTTP and Database Calls
← Back to Go Academy