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,取出時要做型別斷言。
簽名:
  1. func WithValue(parent Context, key, val any) Context

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. type ctxKey int
  7. const requestIDKey ctxKey = 0
  8. func main() {
  9. ctx := context.WithValue(context.Background(), requestIDKey, "req-7f3a")
  10. v := ctx.Value(requestIDKey)
  11. id, ok := v.(string)
  12. fmt.Println(id, ok)
  13. missing := context.Background().Value(requestIDKey)
  14. fmt.Println(missing == nil)
  15. }

輸出:
  1. req-7f3a true
  2. true

注意:key 必須是可比較的型別;傳入 nil 或不可比較的 key(例如切片)時,WithValue 會 panic。

key 的型別


用自訂型別避免衝突


Value 用 == 比對 key,比對時型別也要相同。如果兩個套件都用字串 "id" 當 key,就會互相覆蓋。官方文件明確建議:key 不要用 string 或其他內建型別,而是定義一個未匯出的自訂型別。下面在同一個檔案裡用兩個型別模擬兩個不同套件。
範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. type authKey struct{}
  7. type traceKey struct{}
  8. func main() {
  9. ctx := context.Background()
  10. ctx = context.WithValue(ctx, "id", "user-1")
  11. ctx = context.WithValue(ctx, "id", "trace-9")
  12. fmt.Println("字串 key:", ctx.Value("id"))
  13. ctx2 := context.Background()
  14. ctx2 = context.WithValue(ctx2, authKey{}, "user-1")
  15. ctx2 = context.WithValue(ctx2, traceKey{}, "trace-9")
  16. fmt.Println("authKey:", ctx2.Value(authKey{}))
  17. fmt.Println("traceKey:", ctx2.Value(traceKey{}))
  18. }

輸出:
  1. 字串 key: trace-9
  2. authKey: user-1
  3. traceKey: trace-9

用字串時,後放的 "trace-9" 把前面的使用者 ID 遮住了;用各自的型別時,兩者互不干擾。key 型別常用空結構體 struct{},指派給 any 時不會額外配置記憶體。

提供型別安全的存取函式


慣用做法是把 key 藏起來(未匯出),只對外提供一對函式:NewContext 負責放入、FromContext 負責取出並做型別斷言。呼叫端完全碰不到 key,也不會放錯型別。
範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. type User struct {
  7. ID int
  8. Name string
  9. }
  10. type userKey struct{}
  11. func NewContext(ctx context.Context, u *User) context.Context {
  12. return context.WithValue(ctx, userKey{}, u)
  13. }
  14. func FromContext(ctx context.Context) (*User, bool) {
  15. u, ok := ctx.Value(userKey{}).(*User)
  16. return u, ok
  17. }
  18. func greet(ctx context.Context) string {
  19. u, ok := FromContext(ctx)
  20. if !ok {
  21. return "你好,訪客"
  22. }
  23. return fmt.Sprintf("你好,%s(#%d)", u.Name, u.ID)
  24. }
  25. func main() {
  26. fmt.Println(greet(context.Background()))
  27. ctx := NewContext(context.Background(), &User{ID: 7, Name: "Ada"})
  28. fmt.Println(greet(ctx))
  29. }

輸出:
  1. 你好,訪客
  2. 你好,Ada(#7)

實際專案中,這兩個函式會放在一個獨立套件(例如 user),呼叫端寫成 user.NewContext、user.FromContext。

查找沿著父鏈往上


每次 WithValue 都是包一層新的 context,原本的不會被修改。Value 從最內層開始找,找不到就往父 context 問,一路問到根。所以子 context 可以「遮蔽」父 context 的同名 key,而父 context 完全不受影響。
範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. type localeKey struct{}
  7. func locale(ctx context.Context) string {
  8. if v, ok := ctx.Value(localeKey{}).(string); ok {
  9. return v
  10. }
  11. return "未設定"
  12. }
  13. func main() {
  14. root := context.Background()
  15. tw := context.WithValue(root, localeKey{}, "zh-TW")
  16. jp := context.WithValue(tw, localeKey{}, "ja-JP")
  17. cancelable, cancel := context.WithCancel(tw)
  18. defer cancel()
  19. fmt.Println("root:", locale(root))
  20. fmt.Println("tw:", locale(tw))
  21. fmt.Println("jp:", locale(jp))
  22. fmt.Println("tw 衍生的可取消 context:", locale(cancelable))
  23. }

輸出:
  1. root: 未設定
  2. tw: zh-TW
  3. jp: ja-JP
  4. tw 衍生的可取消 context: zh-TW

值會穿過 WithCancel 等其他衍生函式繼續往下傳。因為查找是逐層往上,鏈很長時會變慢;context 值只適合放少量資料。

實際應用:HTTP 請求 ID


在 middleware 放入、在 handler 取出


最典型的用法:在 HTTP 中介層(middleware) 為每個請求產生或讀取請求 ID,放進 r.Context(),下游的 handler 與它呼叫的函式都能取得,用來寫日誌或傳給其他服務。範例用 httptest 起本機伺服器。
範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. )
  9. type requestIDKey struct{}
  10. func withRequestID(next http.Handler) http.Handler {
  11. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  12. id := r.Header.Get("X-Request-ID")
  13. if id == "" {
  14. id = "generated"
  15. }
  16. ctx := context.WithValue(r.Context(), requestIDKey{}, id)
  17. next.ServeHTTP(w, r.WithContext(ctx))
  18. })
  19. }
  20. func requestID(ctx context.Context) string {
  21. id, _ := ctx.Value(requestIDKey{}).(string)
  22. return id
  23. }
  24. func loadProfile(ctx context.Context) string {
  25. return "[" + requestID(ctx) + "] 讀取個人資料"
  26. }
  27. func main() {
  28. mux := http.NewServeMux()
  29. mux.HandleFunc("/profile", func(w http.ResponseWriter, r *http.Request) {
  30. fmt.Fprintln(w, loadProfile(r.Context()))
  31. })
  32. srv := httptest.NewServer(withRequestID(mux))
  33. defer srv.Close()
  34. for _, id := range []string{"abc-123", ""} {
  35. req, err := http.NewRequest(http.MethodGet, srv.URL+"/profile", nil)
  36. if err != nil {
  37. fmt.Println(err)
  38. return
  39. }
  40. if id != "" {
  41. req.Header.Set("X-Request-ID", id)
  42. }
  43. resp, err := http.DefaultClient.Do(req)
  44. if err != nil {
  45. fmt.Println(err)
  46. return
  47. }
  48. body, _ := io.ReadAll(resp.Body)
  49. resp.Body.Close()
  50. fmt.Print(string(body))
  51. }
  52. }

輸出:
  1. [abc-123] 讀取個人資料
  2. [generated] 讀取個人資料

r.WithContext(ctx) 會產生一個帶著新 context 的請求複本,原本的 r 不變。

不要放可選參數


參數就寫在簽名上


把函式的選項塞進 context,簽名看起來乾淨,但呼叫端完全看不出要傳什麼、型別也沒有檢查,漏放時只會默默用預設值。下面比較兩種寫法:前者從 context 偷拿「每頁筆數」,後者明確寫在參數上。
範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. type pageSizeKey struct{}
  7. func listUsersBad(ctx context.Context) []string {
  8. size, ok := ctx.Value(pageSizeKey{}).(int)
  9. if !ok {
  10. size = 2
  11. }
  12. all := []string{"ann", "bob", "cid", "dan", "eve"}
  13. return all[:min(size, len(all))]
  14. }
  15. type ListOptions struct {
  16. PageSize int
  17. }
  18. func listUsers(ctx context.Context, opts ListOptions) ([]string, error) {
  19. if err := ctx.Err(); err != nil {
  20. return nil, err
  21. }
  22. if opts.PageSize <= 0 {
  23. return nil, fmt.Errorf("PageSize 必須大於 0,收到 %d", opts.PageSize)
  24. }
  25. all := []string{"ann", "bob", "cid", "dan", "eve"}
  26. return all[:min(opts.PageSize, len(all))], nil
  27. }
  28. func main() {
  29. ctx := context.WithValue(context.Background(), pageSizeKey{}, "3")
  30. fmt.Println("藏在 context:", listUsersBad(ctx))
  31. fmt.Println(listUsers(context.Background(), ListOptions{PageSize: 3}))
  32. fmt.Println(listUsers(context.Background(), ListOptions{}))
  33. }

輸出:
  1. 藏在 context: [ann bob]
  2. [ann bob cid] <nil>
  3. [] PageSize 必須大於 0,收到 0

呼叫端把 "3"(字串)放進 context,listUsersBad 的型別斷言失敗,悄悄退回預設的 2 筆,沒有任何錯誤。改成 ListOptions 參數後,型別錯誤在編譯期就會被擋下,不合理的值也能明確回報。min 是 Go 1.21 起的內建函式。

實務守則


守則原因
ctx 放第一個參數,名為 ctx標準庫與社群一致的慣例
不要把 context 存在結構體欄位context 屬於「一次呼叫」,存起來會讓生命週期混亂
不要傳 nil,不確定就用 context.TODO()下游呼叫方法時會 panic
同一個 ctx 可以傳給多個 goroutineContext 可安全地被並行使用
值只放請求範圍的資料依賴與選項應明確寫在參數或結構體上

每個方法都接收 ctx,而不是存在結構體裡


結構體代表長期存在的物件(例如一個 API 客戶端),而 context 代表「這一次呼叫」。把 ctx 存在欄位裡,所有方法就被綁在同一個取消訊號上,無法各自設定逾時。正確做法是每個方法都接收自己的 ctx。
範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. type Client struct {
  8. baseURL string
  9. }
  10. func (c *Client) Get(ctx context.Context, path string) (string, error) {
  11. select {
  12. case <-ctx.Done():
  13. return "", fmt.Errorf("GET %s%s: %w", c.baseURL, path, ctx.Err())
  14. case <-time.After(20 * time.Millisecond):
  15. return "200 OK " + path, nil
  16. }
  17. }
  18. func show(res string, err error) {
  19. if err != nil {
  20. fmt.Println("錯誤:", err)
  21. return
  22. }
  23. fmt.Println("成功:", res)
  24. }
  25. func main() {
  26. c := &Client{baseURL: "https://api.example.com"}
  27. ctx1, cancel1 := context.WithTimeout(context.Background(), time.Second)
  28. defer cancel1()
  29. show(c.Get(ctx1, "/users"))
  30. ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Millisecond)
  31. defer cancel2()
  32. show(c.Get(ctx2, "/reports"))
  33. }

輸出:
  1. 成功: 200 OK /users
  2. 錯誤: GET https://api.example.com/reports: context deadline exceeded

同一個 Client,兩次呼叫各自有不同的期限,互不影響。範例沒有連線,time.After 只是模擬請求耗時。

WithoutCancel:請求結束後仍要做的工作(Go 1.21 起)


有時請求已經回應了,還要在背景做收尾(例如寫稽核日誌),而且希望保留請求 ID 等值。直接用 r.Context() 的話,請求一結束它就被取消;改用 context.WithoutCancel(ctx),就能得到一個保留所有值、但不會隨父 context 取消的 context。
簽名:
  1. func WithoutCancel(parent Context) Context

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. type requestIDKey struct{}
  7. func audit(ctx context.Context, done chan<- string) {
  8. id, _ := ctx.Value(requestIDKey{}).(string)
  9. done <- fmt.Sprintf("稽核紀錄 %s,ctx.Err()=%v", id, ctx.Err())
  10. }
  11. func main() {
  12. reqCtx, cancel := context.WithCancel(context.Background())
  13. reqCtx = context.WithValue(reqCtx, requestIDKey{}, "req-42")
  14. bg := context.WithoutCancel(reqCtx)
  15. cancel()
  16. fmt.Println("請求 ctx:", reqCtx.Err())
  17. done := make(chan string)
  18. go audit(bg, done)
  19. fmt.Println(<-done)
  20. }

輸出:
  1. 請求 ctx: context canceled
  2. 稽核紀錄 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 保留值、脫離取消,做請求結束後的收尾

資料來源