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).
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
