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 是一個介面,只有四個方法:簽名:
- type Context interface {
- Deadline() (deadline time.Time, ok bool)
- Done() <-chan struct{}
- Err() error
- Value(key any) any
- }
| 方法 | 意義 |
|---|---|
Deadline | 有截止時間時回傳該時間與 true;沒有則 ok 為 false |
Done | 回傳一個 channel,context 被取消或逾時時會被關閉;永遠不會被取消的 context 回傳 nil |
Err | Done 還沒關閉時回傳 nil;關閉後回傳 context.Canceled 或 context.DeadlineExceeded |
Value | 取出附帶的值,見 context 值與實務 |
範例:
- package main
- import (
- "context"
- "fmt"
- )
- func describe(name string, ctx context.Context) {
- _, hasDeadline := ctx.Deadline()
- fmt.Printf("%s: 有截止時間=%v Done 為 nil=%v Err=%v\n",
- name, hasDeadline, ctx.Done() == nil, ctx.Err())
- }
- func main() {
- describe("Background", context.Background())
- ctx, cancel := context.WithCancel(context.Background())
- describe("取消前", ctx)
- cancel()
- describe("取消後", ctx)
- }
輸出:
- Background: 有截止時間=false Done 為 nil=true Err=<nil>
- 取消前: 有截止時間=false Done 為 nil=false Err=<nil>
- 取消後: 有截止時間=false Done 為 nil=false Err=context canceled
WithCancel 會從既有的 context 衍生出一個可取消的新 context,細節見取消與逾時。Context 的方法可以被多個 goroutine 同時呼叫。根 context:Background 與 TODO
每棵 context 樹都要有一個起點。
context 套件提供兩個「空」的根 context:永遠不會被取消、沒有截止時間、沒有任何值。Background
context.Background() 用在程式的最上層:main 函式、初始化、測試,以及收到請求時作為起點。簽名:
- func Background() Context
範例:
- package main
- import (
- "context"
- "fmt"
- )
- func main() {
- ctx := context.Background()
- fmt.Println(ctx)
- fmt.Println("Err:", ctx.Err())
- fmt.Println("Value:", ctx.Value("anything"))
- }
輸出:
- context.Background
- Err: <nil>
- Value: <nil>
TODO
context.TODO() 的行為和 Background 完全一樣,差別只在意圖:它表示「這裡應該要有 context,但我還不確定要從哪裡拿」。常見於把舊程式碼逐步改成支援 context 的過渡期,方便之後用搜尋找出來補上。簽名:
- func TODO() Context
範例:
- package main
- import (
- "context"
- "fmt"
- )
- func legacyLookup(id int) string {
- return lookup(context.TODO(), id)
- }
- func lookup(ctx context.Context, id int) string {
- if err := ctx.Err(); err != nil {
- return err.Error()
- }
- return fmt.Sprintf("user-%d", id)
- }
- func main() {
- fmt.Println(context.TODO())
- fmt.Println(legacyLookup(42))
- }
輸出:
- context.TODO
- user-42
| 選擇 | 時機 |
|---|---|
Background() | 確定這裡就是起點(main、測試、背景排程) |
TODO() | 暫時沒有可傳的 context,之後要補 |
注意:不要傳
nil 當作 context。不確定時傳 context.TODO(),否則下游一呼叫 ctx.Done() 就會 panic。把 ctx 當第一個參數
命名與位置的慣例
Go 社群與標準庫的一致慣例:
- 需要 context 的函式,把它放在第一個參數,命名為
ctx - 型別直接寫
context.Context,不要用指標 - 一路往下傳,每一層都把收到的
ctx(或從它衍生的 context)傳給下一層
這樣只要在最上層取消,整條呼叫鏈都會收到通知。
範例:
- package main
- import (
- "context"
- "errors"
- "fmt"
- )
- func handleOrder(ctx context.Context, id string) error {
- if err := checkStock(ctx, id); err != nil {
- return fmt.Errorf("handleOrder %s: %w", id, err)
- }
- return charge(ctx, id)
- }
- func checkStock(ctx context.Context, id string) error {
- if err := ctx.Err(); err != nil {
- return fmt.Errorf("checkStock: %w", err)
- }
- fmt.Println("庫存確認:", id)
- return nil
- }
- func charge(ctx context.Context, id string) error {
- if err := ctx.Err(); err != nil {
- return fmt.Errorf("charge: %w", err)
- }
- fmt.Println("付款完成:", id)
- return nil
- }
- func main() {
- fmt.Println(handleOrder(context.Background(), "A100"))
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
- err := handleOrder(ctx, "A200")
- fmt.Println(err)
- fmt.Println("是取消造成的:", errors.Is(err, context.Canceled))
- }
輸出:
- 庫存確認: A100
- 付款完成: A100
- <nil>
- handleOrder A200: checkStock: context canceled
- 是取消造成的: true
被取消時,錯誤一路用
%w 包裝往上回傳,呼叫端用 errors.Is(err, context.Canceled) 就能判斷原因。用 select 監聽 Done
在迴圈或長時間的工作中,用 select 同時等「下一件事」和
ctx.Done()。Done 一關閉就立刻收手,並回傳 ctx.Err()。範例:
- package main
- import (
- "context"
- "fmt"
- )
- func produce(ctx context.Context, out chan<- int) error {
- defer close(out)
- for i := 1; ; i++ {
- select {
- case <-ctx.Done():
- return ctx.Err()
- case out <- i:
- }
- }
- }
- func main() {
- ctx, cancel := context.WithCancel(context.Background())
- nums := make(chan int)
- errc := make(chan error, 1)
- go func() {
- errc <- produce(ctx, nums)
- }()
- for n := range nums {
- fmt.Println("收到", n)
- if n == 3 {
- cancel()
- break
- }
- }
- fmt.Println("produce 結束:", <-errc)
- }
輸出:
- 收到 1
- 收到 2
- 收到 3
- produce 結束: context canceled
main 取消後就不再接收;produce 卡在送出時,select 會選到 ctx.Done() 而正常結束,不會變成洩漏的 goroutine。context 是一棵樹
取消往下傳,不往上傳
每個
WithXxx 函式都從一個父 context 衍生出子 context。規則是:- 父 context 被取消 → 所有子孫都跟著被取消
- 子 context 被取消 → 父 context 和兄弟不受影響
範例:
- package main
- import (
- "context"
- "fmt"
- )
- func main() {
- root, cancelRoot := context.WithCancel(context.Background())
- defer cancelRoot()
- a, cancelA := context.WithCancel(root)
- defer cancelA()
- b, cancelB := context.WithCancel(root)
- defer cancelB()
- a1, cancelA1 := context.WithCancel(a)
- defer cancelA1()
- show := func(label string) {
- fmt.Printf("[%s] root=%v a=%v a1=%v b=%v\n", label, root.Err(), a.Err(), a1.Err(), b.Err())
- }
- show("初始")
- cancelA()
- show("取消 a")
- cancelRoot()
- show("取消 root")
- }
輸出:
- [初始] root=<nil> a=<nil> a1=<nil> b=<nil>
- [取消 a] root=<nil> a=context canceled a1=context canceled b=<nil>
- [取消 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 傳進去,取消時這些操作就會提早結束並回傳錯誤。範例:
- package main
- import (
- "context"
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- )
- func fetch(ctx context.Context, url string) (string, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
- if err != nil {
- return "", err
- }
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return "", err
- }
- defer resp.Body.Close()
- b, err := io.ReadAll(resp.Body)
- return string(b), err
- }
- func main() {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "pong")
- }))
- defer srv.Close()
- body, err := fetch(context.Background(), srv.URL)
- fmt.Println(body, err)
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
- _, err = fetch(ctx, srv.URL)
- fmt.Println("已取消的請求:", errors.Is(err, context.Canceled))
- }
輸出:
- pong <nil>
- 已取消的請求: true
在 HTTP 伺服器端,
r.Context() 會在客戶端斷線或請求結束時被取消,handler 應該把它傳給下游。重點整理
- context 在呼叫鏈中傳遞「取消訊號、截止時間、請求範圍的值」
Background()是最上層的起點,TODO()表示暫時還沒有可用的 context;不要傳nil- 慣例:
ctx context.Context放在第一個參數,一路往下傳 - 用
select監聽ctx.Done(),取消後回傳ctx.Err() - 取消由父往子傳遞,子 context 的取消不影響父 context