context 值與實務
最後更新
context.WithValue 該怎麼用、key 為什麼要自訂型別、哪些東西不該放進 context,以及日常使用 context 的守則。WithValue 是什麼
除了取消與逾時,context 還能夾帶值。它的用途很窄:傳遞請求範圍(request-scoped) 的資料,也就是「屬於這一次請求、跨越多層 API 都需要知道」的資訊。
| 適合放進 context | 不適合 |
|---|---|
| 請求 ID、追蹤(trace)ID | 函式的可選參數、設定選項 |
| 已驗證的使用者身分 | 資料庫連線、logger 等依賴 |
| 請求的語系、租戶代號 | 業務資料(訂單、商品) |
判斷原則:如果拿掉這個值,函式的邏輯結果就會改變,那它就是參數,應該寫在函式簽名上。
WithValue 與 Value
WithValue 從父 context 衍生出一個帶有「key → 值」的新 context;Value(key) 取出對應的值,沒有就回傳 nil。回傳型別是 any,取出時要做型別斷言。簽名:
- func WithValue(parent Context, key, val any) Context
範例:
- package main
- import (
- "context"
- "fmt"
- )
- type ctxKey int
- const requestIDKey ctxKey = 0
- func main() {
- ctx := context.WithValue(context.Background(), requestIDKey, "req-7f3a")
- v := ctx.Value(requestIDKey)
- id, ok := v.(string)
- fmt.Println(id, ok)
- missing := context.Background().Value(requestIDKey)
- fmt.Println(missing == nil)
- }
輸出:
- req-7f3a true
- true
注意:key 必須是可比較的型別;傳入
nil 或不可比較的 key(例如切片)時,WithValue 會 panic。key 的型別
用自訂型別避免衝突
Value 用 == 比對 key,比對時型別也要相同。如果兩個套件都用字串 "id" 當 key,就會互相覆蓋。官方文件明確建議:key 不要用 string 或其他內建型別,而是定義一個未匯出的自訂型別。下面在同一個檔案裡用兩個型別模擬兩個不同套件。範例:
- package main
- import (
- "context"
- "fmt"
- )
- type authKey struct{}
- type traceKey struct{}
- func main() {
- ctx := context.Background()
- ctx = context.WithValue(ctx, "id", "user-1")
- ctx = context.WithValue(ctx, "id", "trace-9")
- fmt.Println("字串 key:", ctx.Value("id"))
- ctx2 := context.Background()
- ctx2 = context.WithValue(ctx2, authKey{}, "user-1")
- ctx2 = context.WithValue(ctx2, traceKey{}, "trace-9")
- fmt.Println("authKey:", ctx2.Value(authKey{}))
- fmt.Println("traceKey:", ctx2.Value(traceKey{}))
- }
輸出:
- 字串 key: trace-9
- authKey: user-1
- traceKey: trace-9
用字串時,後放的
"trace-9" 把前面的使用者 ID 遮住了;用各自的型別時,兩者互不干擾。key 型別常用空結構體 struct{},指派給 any 時不會額外配置記憶體。提供型別安全的存取函式
慣用做法是把 key 藏起來(未匯出),只對外提供一對函式:
NewContext 負責放入、FromContext 負責取出並做型別斷言。呼叫端完全碰不到 key,也不會放錯型別。範例:
- package main
- import (
- "context"
- "fmt"
- )
- type User struct {
- ID int
- Name string
- }
- type userKey struct{}
- func NewContext(ctx context.Context, u *User) context.Context {
- return context.WithValue(ctx, userKey{}, u)
- }
- func FromContext(ctx context.Context) (*User, bool) {
- u, ok := ctx.Value(userKey{}).(*User)
- return u, ok
- }
- func greet(ctx context.Context) string {
- u, ok := FromContext(ctx)
- if !ok {
- return "你好,訪客"
- }
- return fmt.Sprintf("你好,%s(#%d)", u.Name, u.ID)
- }
- func main() {
- fmt.Println(greet(context.Background()))
- ctx := NewContext(context.Background(), &User{ID: 7, Name: "Ada"})
- fmt.Println(greet(ctx))
- }
輸出:
- 你好,訪客
- 你好,Ada(#7)
實際專案中,這兩個函式會放在一個獨立套件(例如
user),呼叫端寫成 user.NewContext、user.FromContext。查找沿著父鏈往上
每次
WithValue 都是包一層新的 context,原本的不會被修改。Value 從最內層開始找,找不到就往父 context 問,一路問到根。所以子 context 可以「遮蔽」父 context 的同名 key,而父 context 完全不受影響。範例:
- package main
- import (
- "context"
- "fmt"
- )
- type localeKey struct{}
- func locale(ctx context.Context) string {
- if v, ok := ctx.Value(localeKey{}).(string); ok {
- return v
- }
- return "未設定"
- }
- func main() {
- root := context.Background()
- tw := context.WithValue(root, localeKey{}, "zh-TW")
- jp := context.WithValue(tw, localeKey{}, "ja-JP")
- cancelable, cancel := context.WithCancel(tw)
- defer cancel()
- fmt.Println("root:", locale(root))
- fmt.Println("tw:", locale(tw))
- fmt.Println("jp:", locale(jp))
- fmt.Println("tw 衍生的可取消 context:", locale(cancelable))
- }
輸出:
- root: 未設定
- tw: zh-TW
- jp: ja-JP
- tw 衍生的可取消 context: zh-TW
值會穿過
WithCancel 等其他衍生函式繼續往下傳。因為查找是逐層往上,鏈很長時會變慢;context 值只適合放少量資料。實際應用:HTTP 請求 ID
在 middleware 放入、在 handler 取出
最典型的用法:在 HTTP 中介層(middleware) 為每個請求產生或讀取請求 ID,放進
r.Context(),下游的 handler 與它呼叫的函式都能取得,用來寫日誌或傳給其他服務。範例用 httptest 起本機伺服器。範例:
- package main
- import (
- "context"
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- )
- type requestIDKey struct{}
- func withRequestID(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- id := r.Header.Get("X-Request-ID")
- if id == "" {
- id = "generated"
- }
- ctx := context.WithValue(r.Context(), requestIDKey{}, id)
- next.ServeHTTP(w, r.WithContext(ctx))
- })
- }
- func requestID(ctx context.Context) string {
- id, _ := ctx.Value(requestIDKey{}).(string)
- return id
- }
- func loadProfile(ctx context.Context) string {
- return "[" + requestID(ctx) + "] 讀取個人資料"
- }
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("/profile", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintln(w, loadProfile(r.Context()))
- })
- srv := httptest.NewServer(withRequestID(mux))
- defer srv.Close()
- for _, id := range []string{"abc-123", ""} {
- req, err := http.NewRequest(http.MethodGet, srv.URL+"/profile", nil)
- if err != nil {
- fmt.Println(err)
- return
- }
- if id != "" {
- req.Header.Set("X-Request-ID", id)
- }
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Print(string(body))
- }
- }
輸出:
- [abc-123] 讀取個人資料
- [generated] 讀取個人資料
r.WithContext(ctx) 會產生一個帶著新 context 的請求複本,原本的 r 不變。不要放可選參數
參數就寫在簽名上
把函式的選項塞進 context,簽名看起來乾淨,但呼叫端完全看不出要傳什麼、型別也沒有檢查,漏放時只會默默用預設值。下面比較兩種寫法:前者從 context 偷拿「每頁筆數」,後者明確寫在參數上。
範例:
- package main
- import (
- "context"
- "fmt"
- )
- type pageSizeKey struct{}
- func listUsersBad(ctx context.Context) []string {
- size, ok := ctx.Value(pageSizeKey{}).(int)
- if !ok {
- size = 2
- }
- all := []string{"ann", "bob", "cid", "dan", "eve"}
- return all[:min(size, len(all))]
- }
- type ListOptions struct {
- PageSize int
- }
- func listUsers(ctx context.Context, opts ListOptions) ([]string, error) {
- if err := ctx.Err(); err != nil {
- return nil, err
- }
- if opts.PageSize <= 0 {
- return nil, fmt.Errorf("PageSize 必須大於 0,收到 %d", opts.PageSize)
- }
- all := []string{"ann", "bob", "cid", "dan", "eve"}
- return all[:min(opts.PageSize, len(all))], nil
- }
- func main() {
- ctx := context.WithValue(context.Background(), pageSizeKey{}, "3")
- fmt.Println("藏在 context:", listUsersBad(ctx))
- fmt.Println(listUsers(context.Background(), ListOptions{PageSize: 3}))
- fmt.Println(listUsers(context.Background(), ListOptions{}))
- }
輸出:
- 藏在 context: [ann bob]
- [ann bob cid] <nil>
- [] PageSize 必須大於 0,收到 0
呼叫端把
"3"(字串)放進 context,listUsersBad 的型別斷言失敗,悄悄退回預設的 2 筆,沒有任何錯誤。改成 ListOptions 參數後,型別錯誤在編譯期就會被擋下,不合理的值也能明確回報。min 是 Go 1.21 起的內建函式。實務守則
| 守則 | 原因 |
|---|---|
ctx 放第一個參數,名為 ctx | 標準庫與社群一致的慣例 |
| 不要把 context 存在結構體欄位 | context 屬於「一次呼叫」,存起來會讓生命週期混亂 |
不要傳 nil,不確定就用 context.TODO() | 下游呼叫方法時會 panic |
| 同一個 ctx 可以傳給多個 goroutine | Context 可安全地被並行使用 |
| 值只放請求範圍的資料 | 依賴與選項應明確寫在參數或結構體上 |
每個方法都接收 ctx,而不是存在結構體裡
結構體代表長期存在的物件(例如一個 API 客戶端),而 context 代表「這一次呼叫」。把 ctx 存在欄位裡,所有方法就被綁在同一個取消訊號上,無法各自設定逾時。正確做法是每個方法都接收自己的 ctx。
範例:
- package main
- import (
- "context"
- "fmt"
- "time"
- )
- type Client struct {
- baseURL string
- }
- func (c *Client) Get(ctx context.Context, path string) (string, error) {
- select {
- case <-ctx.Done():
- return "", fmt.Errorf("GET %s%s: %w", c.baseURL, path, ctx.Err())
- case <-time.After(20 * time.Millisecond):
- return "200 OK " + path, nil
- }
- }
- func show(res string, err error) {
- if err != nil {
- fmt.Println("錯誤:", err)
- return
- }
- fmt.Println("成功:", res)
- }
- func main() {
- c := &Client{baseURL: "https://api.example.com"}
- ctx1, cancel1 := context.WithTimeout(context.Background(), time.Second)
- defer cancel1()
- show(c.Get(ctx1, "/users"))
- ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Millisecond)
- defer cancel2()
- show(c.Get(ctx2, "/reports"))
- }
輸出:
- 成功: 200 OK /users
- 錯誤: GET https://api.example.com/reports: context deadline exceeded
同一個
Client,兩次呼叫各自有不同的期限,互不影響。範例沒有連線,time.After 只是模擬請求耗時。WithoutCancel:請求結束後仍要做的工作(Go 1.21 起)
有時請求已經回應了,還要在背景做收尾(例如寫稽核日誌),而且希望保留請求 ID 等值。直接用
r.Context() 的話,請求一結束它就被取消;改用 context.WithoutCancel(ctx),就能得到一個保留所有值、但不會隨父 context 取消的 context。簽名:
- func WithoutCancel(parent Context) Context
範例:
- package main
- import (
- "context"
- "fmt"
- )
- type requestIDKey struct{}
- func audit(ctx context.Context, done chan<- string) {
- id, _ := ctx.Value(requestIDKey{}).(string)
- done <- fmt.Sprintf("稽核紀錄 %s,ctx.Err()=%v", id, ctx.Err())
- }
- func main() {
- reqCtx, cancel := context.WithCancel(context.Background())
- reqCtx = context.WithValue(reqCtx, requestIDKey{}, "req-42")
- bg := context.WithoutCancel(reqCtx)
- cancel()
- fmt.Println("請求 ctx:", reqCtx.Err())
- done := make(chan string)
- go audit(bg, done)
- fmt.Println(<-done)
- }
輸出:
- 請求 ctx: context canceled
- 稽核紀錄 req-42,ctx.Err()=<nil>
注意:
WithoutCancel 回傳的 context 沒有截止時間、Done() 為 nil,背景工作如果需要時限,要自己再包一層 WithTimeout。重點整理
- context 值只放請求範圍的資料(請求 ID、使用者身分),不放可選參數或依賴
- key 用未匯出的自訂型別(常用
struct{}),不要用字串等內建型別 - 對外提供
NewContext/FromContext這類存取函式,把 key 和型別斷言藏起來 Value沿父鏈往上查找,子 context 可遮蔽父的同名 key- 不要把 context 存進結構體、不要傳
nil;每個方法都接收自己的ctx - Go 1.21 起可用
WithoutCancel保留值、脫離取消,做請求結束後的收尾