context 基礎

最後更新


context.Context 是什麼、為什麼幾乎每個 I/O 函式都把它放在第一個參數,以及 Background 與 TODO 的差別。

為什麼需要 context


想像一個 HTTP 請求進來,處理它的程式要查資料庫、呼叫另一個服務、讀快取,每一步可能又開了自己的 goroutine。這時使用者關掉了瀏覽器:
  • 這些還在跑的工作應該停下來,不然只是白白浪費資源
  • 但它們分散在好幾層函式、好幾個 goroutine 裡,要怎麼一次通知全部?

context(上下文) 就是 Go 對這個問題的標準答案。它像一張跟著請求一路傳下去的「工作單」,上面寫著:
資訊方法
這件工作是否已被取消Done()、Err()
最晚什麼時候必須完成Deadline()
附帶的請求範圍資料(如請求 ID)Value(key)

任何一層只要拿著這張工作單,就能知道「該不該繼續做」。自己實作 done channel 也能做到取消,但 context 把它標準化了,標準庫與第三方庫都接受同一種型別。

context.Context 介面


四個方法


context.Context 是一個介面,只有四個方法:
簽名:
  1. type Context interface {
  2. Deadline() (deadline time.Time, ok bool)
  3. Done() <-chan struct{}
  4. Err() error
  5. Value(key any) any
  6. }

方法意義
Deadline有截止時間時回傳該時間與 true;沒有則 ok 為 false
Done回傳一個 channel,context 被取消或逾時時會被關閉;永遠不會被取消的 context 回傳 nil
ErrDone 還沒關閉時回傳 nil;關閉後回傳 context.Canceled 或 context.DeadlineExceeded
Value取出附帶的值,見 context 值與實務

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. func describe(name string, ctx context.Context) {
  7. _, hasDeadline := ctx.Deadline()
  8. fmt.Printf("%s: 有截止時間=%v Done 為 nil=%v Err=%v\n",
  9. name, hasDeadline, ctx.Done() == nil, ctx.Err())
  10. }
  11. func main() {
  12. describe("Background", context.Background())
  13. ctx, cancel := context.WithCancel(context.Background())
  14. describe("取消前", ctx)
  15. cancel()
  16. describe("取消後", ctx)
  17. }

輸出:
  1. Background: 有截止時間=false Done 為 nil=true Err=<nil>
  2. 取消前: 有截止時間=false Done 為 nil=false Err=<nil>
  3. 取消後: 有截止時間=false Done 為 nil=false Err=context canceled

WithCancel 會從既有的 context 衍生出一個可取消的新 context,細節見取消與逾時。Context 的方法可以被多個 goroutine 同時呼叫。

根 context:Background 與 TODO


每棵 context 樹都要有一個起點。context 套件提供兩個「空」的根 context:永遠不會被取消、沒有截止時間、沒有任何值。

Background


context.Background() 用在程式的最上層:main 函式、初始化、測試,以及收到請求時作為起點。
簽名:
  1. func Background() Context

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. func main() {
  7. ctx := context.Background()
  8. fmt.Println(ctx)
  9. fmt.Println("Err:", ctx.Err())
  10. fmt.Println("Value:", ctx.Value("anything"))
  11. }

輸出:
  1. context.Background
  2. Err: <nil>
  3. Value: <nil>

TODO


context.TODO() 的行為和 Background 完全一樣,差別只在意圖:它表示「這裡應該要有 context,但我還不確定要從哪裡拿」。常見於把舊程式碼逐步改成支援 context 的過渡期,方便之後用搜尋找出來補上。
簽名:
  1. func TODO() Context

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

輸出:
  1. context.TODO
  2. user-42

選擇時機
Background()確定這裡就是起點(main、測試、背景排程)
TODO()暫時沒有可傳的 context,之後要補

注意:不要傳 nil 當作 context。不確定時傳 context.TODO(),否則下游一呼叫 ctx.Done() 就會 panic。

把 ctx 當第一個參數


命名與位置的慣例


Go 社群與標準庫的一致慣例:
  • 需要 context 的函式,把它放在第一個參數,命名為 ctx
  • 型別直接寫 context.Context,不要用指標
  • 一路往下傳,每一層都把收到的 ctx(或從它衍生的 context)傳給下一層

這樣只要在最上層取消,整條呼叫鏈都會收到通知。
範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. )
  7. func handleOrder(ctx context.Context, id string) error {
  8. if err := checkStock(ctx, id); err != nil {
  9. return fmt.Errorf("handleOrder %s: %w", id, err)
  10. }
  11. return charge(ctx, id)
  12. }
  13. func checkStock(ctx context.Context, id string) error {
  14. if err := ctx.Err(); err != nil {
  15. return fmt.Errorf("checkStock: %w", err)
  16. }
  17. fmt.Println("庫存確認:", id)
  18. return nil
  19. }
  20. func charge(ctx context.Context, id string) error {
  21. if err := ctx.Err(); err != nil {
  22. return fmt.Errorf("charge: %w", err)
  23. }
  24. fmt.Println("付款完成:", id)
  25. return nil
  26. }
  27. func main() {
  28. fmt.Println(handleOrder(context.Background(), "A100"))
  29. ctx, cancel := context.WithCancel(context.Background())
  30. cancel()
  31. err := handleOrder(ctx, "A200")
  32. fmt.Println(err)
  33. fmt.Println("是取消造成的:", errors.Is(err, context.Canceled))
  34. }

輸出:
  1. 庫存確認: A100
  2. 付款完成: A100
  3. <nil>
  4. handleOrder A200: checkStock: context canceled
  5. 是取消造成的: true

被取消時,錯誤一路用 %w 包裝往上回傳,呼叫端用 errors.Is(err, context.Canceled) 就能判斷原因。

用 select 監聽 Done


在迴圈或長時間的工作中,用 select 同時等「下一件事」和 ctx.Done()。Done 一關閉就立刻收手,並回傳 ctx.Err()。
範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. func produce(ctx context.Context, out chan<- int) error {
  7. defer close(out)
  8. for i := 1; ; i++ {
  9. select {
  10. case <-ctx.Done():
  11. return ctx.Err()
  12. case out <- i:
  13. }
  14. }
  15. }
  16. func main() {
  17. ctx, cancel := context.WithCancel(context.Background())
  18. nums := make(chan int)
  19. errc := make(chan error, 1)
  20. go func() {
  21. errc <- produce(ctx, nums)
  22. }()
  23. for n := range nums {
  24. fmt.Println("收到", n)
  25. if n == 3 {
  26. cancel()
  27. break
  28. }
  29. }
  30. fmt.Println("produce 結束:", <-errc)
  31. }

輸出:
  1. 收到 1
  2. 收到 2
  3. 收到 3
  4. produce 結束: context canceled

main 取消後就不再接收;produce 卡在送出時,select 會選到 ctx.Done() 而正常結束,不會變成洩漏的 goroutine。

context 是一棵樹


取消往下傳,不往上傳


每個 WithXxx 函式都從一個父 context 衍生出子 context。規則是:
  • 父 context 被取消 → 所有子孫都跟著被取消
  • 子 context 被取消 → 父 context 和兄弟不受影響

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. func main() {
  7. root, cancelRoot := context.WithCancel(context.Background())
  8. defer cancelRoot()
  9. a, cancelA := context.WithCancel(root)
  10. defer cancelA()
  11. b, cancelB := context.WithCancel(root)
  12. defer cancelB()
  13. a1, cancelA1 := context.WithCancel(a)
  14. defer cancelA1()
  15. show := func(label string) {
  16. fmt.Printf("[%s] root=%v a=%v a1=%v b=%v\n", label, root.Err(), a.Err(), a1.Err(), b.Err())
  17. }
  18. show("初始")
  19. cancelA()
  20. show("取消 a")
  21. cancelRoot()
  22. show("取消 root")
  23. }

輸出:
  1. [初始] root=<nil> a=<nil> a1=<nil> b=<nil>
  2. [取消 a] root=<nil> a=context canceled a1=context canceled b=<nil>
  3. [取消 root] root=context canceled a=context canceled a1=context canceled b=context canceled

取消 a 只影響 a 與它的子 a1;取消 root 後,剩下的 b 也跟著被取消。

標準庫中的 context


帶 context 的 HTTP 請求


標準庫中凡是可能等待的操作,大多有接受 context 的版本,例如 http.NewRequestWithContext、net.Dialer.DialContext、database/sql 的 QueryContext、exec.CommandContext。把 ctx 傳進去,取消時這些操作就會提早結束並回傳錯誤。
範例:
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. )
  10. func fetch(ctx context.Context, url string) (string, error) {
  11. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  12. if err != nil {
  13. return "", err
  14. }
  15. resp, err := http.DefaultClient.Do(req)
  16. if err != nil {
  17. return "", err
  18. }
  19. defer resp.Body.Close()
  20. b, err := io.ReadAll(resp.Body)
  21. return string(b), err
  22. }
  23. func main() {
  24. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  25. fmt.Fprint(w, "pong")
  26. }))
  27. defer srv.Close()
  28. body, err := fetch(context.Background(), srv.URL)
  29. fmt.Println(body, err)
  30. ctx, cancel := context.WithCancel(context.Background())
  31. cancel()
  32. _, err = fetch(ctx, srv.URL)
  33. fmt.Println("已取消的請求:", errors.Is(err, context.Canceled))
  34. }

輸出:
  1. pong <nil>
  2. 已取消的請求: true

在 HTTP 伺服器端,r.Context() 會在客戶端斷線或請求結束時被取消,handler 應該把它傳給下游。

重點整理


  • context 在呼叫鏈中傳遞「取消訊號、截止時間、請求範圍的值」
  • Background() 是最上層的起點,TODO() 表示暫時還沒有可用的 context;不要傳 nil
  • 慣例:ctx context.Context 放在第一個參數,一路往下傳
  • 用 select 監聽 ctx.Done(),取消後回傳 ctx.Err()
  • 取消由父往子傳遞,子 context 的取消不影響父 context

資料來源