Golang / GoLang Production Patterns and Web Standards Interview Questions
What is context.Context in Go, what does it carry, and how do you create one?
context.Context is Go's standard mechanism for propagating three things across API boundaries and goroutine boundaries: cancellation signals, deadlines/timeouts, and request-scoped values. Every blocking or long-running function should accept a Context as its first parameter.
// The full context.Context interface: type Context interface { Deadline() (deadline time.Time, ok bool) // zero time if no deadline Done() <-chan struct{} // closed on cancel/timeout Err() error // nil, Canceled, or DeadlineExceeded Value(key any) any // request-scoped value lookup } // Root contexts (start of a context tree) ctx := context.Background() // never cancelled, no deadline â use at program start ctx = context.TODO() // placeholder when context not yet known // Derived contexts â each returns a cancel function ctx1, cancel1 := context.WithCancel(context.Background()) defer cancel1() // ALWAYS defer â prevents goroutine leak in the monitor goroutine ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second) defer cancel2() ctx3, cancel3 := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second)) defer cancel3() // Attaching a value (use typed key to avoid collisions) type ctxKey string const traceIDKey ctxKey = "traceID" ctx4 := context.WithValue(ctx, traceIDKey, "abc-123") traceID := ctx4.Value(traceIDKey).(string) // Propagate context to downstream functions func processRequest(ctx context.Context, req Request) error { if err := validateInput(ctx, req); err != nil { return fmt.Errorf("validation: %w", err) } return persistToDB(ctx, req) // ctx carries cancellation + deadline }
Context tree: cancelling a parent cancels all descendants. A child context with a shorter deadline does not extend the parent's deadline — the effective deadline is always min(parent, child).
More Related questions...