context

最後更新


context 套件在函式呼叫鏈之間傳遞「取消訊號、截止時間與請求範圍的值」,讓一整串工作可以一起停下來。

這個套件做什麼


想像一個 HTTP 請求進來,處理函式去查資料庫、再呼叫另一個 API。如果使用者中途關掉瀏覽器,或是已經超過 3 秒,後面那些工作就應該停止,不要白白浪費資源。
context.Context 就是這個「停止通知」的載體。它從最外層一路往下傳,任何一層都可以檢查「我是不是該停了」。概念介紹見 context 基礎。
Context 介面有四個方法:
方法用途
Done() <-chan struct{}被取消時會關閉的 channel,用在 select
Err() error還沒取消回傳 nil;取消後是 context.Canceled 或 context.DeadlineExceeded
Deadline() (time.Time, bool)截止時間(如果有設定)
Value(key any) any取出請求範圍的值

慣例:
  • ctx context.Context 放在函式的第一個參數,不要存進結構體
  • 每個 WithCancel、WithTimeout 回傳的 cancel 都要呼叫,通常寫 defer cancel(),否則會洩漏資源
  • 不要傳 nil,不確定用什麼就用 context.TODO()

標準庫很多地方都接受 context,例如 net/http 的 Request.Context()、database/sql 的 QueryContext、os/exec 的 CommandContext。

匯入


  1. import "context"

常用 API


Background 與 TODO:根 context


所有 context 都從一個根開始。Background() 是永遠不會被取消、沒有截止時間、沒有值的空 context,用在 main、初始化和測試的最上層。TODO() 行為相同,用來標示「這裡之後要換成正確的 context,現在先放著」。
簽名:
  1. func Background() Context
  2. func TODO() Context

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. func fetchUser(ctx context.Context, id int) (string, error) {
  7. if err := ctx.Err(); err != nil {
  8. return "", err
  9. }
  10. return fmt.Sprintf("user-%d", id), nil
  11. }
  12. func main() {
  13. ctx := context.Background()
  14. name, err := fetchUser(ctx, 42)
  15. fmt.Println(name, err)
  16. fmt.Println(ctx.Done() == nil)
  17. _, hasDeadline := ctx.Deadline()
  18. fmt.Println(hasDeadline)
  19. fmt.Println(context.TODO())
  20. }

輸出:
  1. user-42 <nil>
  2. true
  3. false
  4. context.TODO

WithCancel:手動取消


WithCancel 從父 context 衍生出子 context 和一個 cancel 函式。呼叫 cancel 後,子 context 的 Done() 會關閉,所有監聽它的 goroutine 都能收到通知。父 context 被取消時,子 context 也會跟著被取消。
範例的產生器在背景不斷產生數字,主程式拿到 3 之後呼叫 cancel,背景 goroutine 就會結束,不會洩漏。
簽名:
  1. func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. func generate(ctx context.Context) <-chan int {
  7. ch := make(chan int)
  8. go func() {
  9. defer close(ch)
  10. for i := 1; ; i++ {
  11. select {
  12. case <-ctx.Done():
  13. return
  14. case ch <- i:
  15. }
  16. }
  17. }()
  18. return ch
  19. }
  20. func main() {
  21. ctx, cancel := context.WithCancel(context.Background())
  22. for n := range generate(ctx) {
  23. fmt.Println(n)
  24. if n == 3 {
  25. cancel()
  26. break
  27. }
  28. }
  29. <-ctx.Done()
  30. fmt.Println(ctx.Err())
  31. }

輸出:
  1. 1
  2. 2
  3. 3
  4. context canceled

WithTimeout:限時完成


WithTimeout 在指定時間後自動取消,是最常用的形式:呼叫外部服務、查資料庫都應該設上限。逾時後 Err() 回傳 context.DeadlineExceeded,可用 errors.Is 判斷。
簽名:
  1. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "time"
  7. )
  8. func slowQuery(ctx context.Context) (string, error) {
  9. select {
  10. case <-time.After(time.Second):
  11. return "result", nil
  12. case <-ctx.Done():
  13. return "", ctx.Err()
  14. }
  15. }
  16. func main() {
  17. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
  18. defer cancel()
  19. _, err := slowQuery(ctx)
  20. fmt.Println("error:", err)
  21. fmt.Println(errors.Is(err, context.DeadlineExceeded))
  22. }

輸出:
  1. error: context deadline exceeded
  2. true

WithDeadline:指定截止時刻


WithDeadline 和 WithTimeout 一樣,只是給「幾點幾分截止」而不是「多久之後」。範例的截止時刻已經過去,所以 context 一建立就已經是取消狀態。
子 context 的截止時間不會比父 context 晚:父 context 9 點截止,子 context 就算設一小時後,實際截止時間仍是 9 點。
簽名:
  1. func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. func main() {
  8. deadline := time.Date(2026, time.March, 14, 9, 0, 0, 0, time.UTC)
  9. ctx, cancel := context.WithDeadline(context.Background(), deadline)
  10. defer cancel()
  11. d, ok := ctx.Deadline()
  12. fmt.Println(d, ok)
  13. fmt.Println(ctx.Err())
  14. child, cancelChild := context.WithTimeout(ctx, time.Hour)
  15. defer cancelChild()
  16. cd, _ := child.Deadline()
  17. fmt.Println(cd.Equal(deadline))
  18. }

輸出:
  1. 2026-03-14 09:00:00 +0000 UTC true
  2. context deadline exceeded
  3. true

WithValue:傳遞請求範圍的值


WithValue 把一組鍵值掛在 context 上,往下傳的每一層都能用 Value 讀出。適合放「跟著這次請求走」的資料,例如請求 ID、登入使用者。
鍵要用自訂的未匯出型別,避免和其他套件的鍵撞名;通常再包一對存取函式,讓呼叫端不必知道鍵。不要拿它傳可選參數或相依物件,那些應該是明確的函式參數。詳見 context 值與實務。
簽名:
  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 WithRequestID(ctx context.Context, id string) context.Context {
  9. return context.WithValue(ctx, requestIDKey, id)
  10. }
  11. func RequestID(ctx context.Context) (string, bool) {
  12. id, ok := ctx.Value(requestIDKey).(string)
  13. return id, ok
  14. }
  15. func handle(ctx context.Context) {
  16. if id, ok := RequestID(ctx); ok {
  17. fmt.Println("request id:", id)
  18. return
  19. }
  20. fmt.Println("no request id")
  21. }
  22. func main() {
  23. handle(context.Background())
  24. ctx := WithRequestID(context.Background(), "req-7f3a")
  25. handle(ctx)
  26. }

輸出:
  1. no request id
  2. request id: req-7f3a

WithCancelCause 與 Cause:記錄取消原因


Err() 只能告訴你「被取消了」或「逾時了」。Go 1.20 起,WithCancelCause 的 cancel 可以帶一個 error 說明原因,事後用 context.Cause(ctx) 取出;Go 1.21 起,WithTimeoutCause、WithDeadlineCause 可以指定逾時時的原因。
Err() 的值不變,原有判斷 context.Canceled 的程式碼不受影響。
簽名:
  1. func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)
  2. func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)
  3. func Cause(c Context) error

範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "time"
  7. )
  8. var errShutdown = errors.New("server shutting down")
  9. func main() {
  10. ctx, cancel := context.WithCancelCause(context.Background())
  11. cancel(errShutdown)
  12. fmt.Println(ctx.Err())
  13. fmt.Println(context.Cause(ctx))
  14. tctx, tcancel := context.WithTimeoutCause(context.Background(), 10*time.Millisecond, errors.New("payment API too slow"))
  15. defer tcancel()
  16. <-tctx.Done()
  17. fmt.Println(tctx.Err())
  18. fmt.Println(context.Cause(tctx))
  19. }

輸出:
  1. context canceled
  2. server shutting down
  3. context deadline exceeded
  4. payment API too slow

AfterFunc:取消時執行清理


Go 1.21 起,AfterFunc(ctx, f) 在 ctx 被取消後,於另一個 goroutine 執行 f,不必自己寫一個 goroutine 去等 Done()。回傳的 stop 可以取消這個安排,回傳 true 表示成功阻止 f 執行。
簽名:
  1. func AfterFunc(ctx Context, f func()) (stop func() bool)

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. func main() {
  7. ctx, cancel := context.WithCancel(context.Background())
  8. done := make(chan struct{})
  9. context.AfterFunc(ctx, func() {
  10. fmt.Println("releasing resources")
  11. close(done)
  12. })
  13. other, cancelOther := context.WithCancel(context.Background())
  14. stop := context.AfterFunc(other, func() {
  15. fmt.Println("never printed")
  16. })
  17. fmt.Println("stopped:", stop())
  18. cancelOther()
  19. cancel()
  20. <-done
  21. fmt.Println("done")
  22. }

輸出:
  1. stopped: true
  2. releasing resources
  3. done

WithoutCancel:切斷取消但保留值


Go 1.21 起,WithoutCancel 衍生出一個不會隨父 context 取消的 context,但仍能讀到父 context 的值。用在請求結束後還要繼續做的事,例如寫稽核記錄:請求已經結束、context 被取消了,記錄仍要寫完,而且需要請求 ID。
注意:這樣的 context 沒有截止時間,需要時自己再包一層 WithTimeout。
簽名:
  1. func WithoutCancel(parent Context) Context

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. type ctxKey string
  7. func main() {
  8. parent, cancel := context.WithCancel(context.WithValue(context.Background(), ctxKey("user"), "alice"))
  9. detached := context.WithoutCancel(parent)
  10. cancel()
  11. fmt.Println(parent.Err())
  12. fmt.Println(detached.Err())
  13. fmt.Println(detached.Value(ctxKey("user")))
  14. }

輸出:
  1. context canceled
  2. <nil>
  3. alice

重點整理


  • context 從呼叫鏈最上層一路往下傳,放在第一個參數
  • WithCancel、WithTimeout、WithDeadline 回傳的 cancel 一定要呼叫
  • 被取消時 Done() 關閉,Err() 是 Canceled 或 DeadlineExceeded
  • WithValue 只放請求範圍的資料,鍵用未匯出的自訂型別
  • 要知道為什麼被取消用 WithCancelCause 與 Cause;取消後的清理用 AfterFunc

資料來源