漫行记Wandering
Journal 1,217 字 5 分钟 Golang

Golang Context

Heads up: Just copy some content from official doc as a note to myself.

Context is a powerful feature in Go that can carry deadlines, cancellation signals, and request-scoped values across API boundaries and between processes. So it provides the ability to gracefully cancel long-running operations, set timeouts, and pass metadata through call chains, enabling better resource management and request lifecycle control.

How to use context

Basically, there are two opinions, one is to put context in struct, another is to pass context as function parameter. The official doc suggests to pass context as function parameter, and context should be the first parameter in the function signature.

Context as function parameter

Here are the benefits:

Per-call control: Each invocation can have independent deadlines, cancellation, and metadata

Clear semantics: The scope and usage are immediately apparent

Maximum flexibility: Callers have full control over context behavior

Context in struct

Here are the issues:

Lost granularity: Cannot set call-specific timeouts or cancellation

Lifetime confusion: Mingles struct lifetime with method call lifetime

API ambiguity: Users unclear about context scope and application

Production risks: Resource exhaustion due to inability to cancel individual requests

Official doc

context package

Go Blog: Contexts and structs

← 随笔