# context

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

## 這個套件做什麼

想像一個 HTTP 請求進來，處理函式去查資料庫、再呼叫另一個 API。如果使用者中途關掉瀏覽器，或是已經超過 3 秒，後面那些工作就應該停止，不要白白浪費資源。

`context.Context` 就是這個「停止通知」的載體。它從最外層一路往下傳，任何一層都可以檢查「我是不是該停了」。概念介紹見 [context 基礎](/context-basics)。

`Context` 介面有四個方法：

| 方法 | 用途 |
| --- | --- |
| `Done() <-chan struct{}` | 被取消時會關閉的 channel，用在 [select](/concurrency-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](/pkg-net-http) 的 `Request.Context()`、[database/sql](/pkg-database-sql) 的 `QueryContext`、[os/exec](/pkg-os-exec) 的 `CommandContext`。

## 匯入

```go
import "context"
```

## 常用 API

### Background 與 TODO：根 context

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

簽名：
```go
func Background() Context
func TODO() Context
```

範例：
```go
package main

import (
	"context"
	"fmt"
)

func fetchUser(ctx context.Context, id int) (string, error) {
	if err := ctx.Err(); err != nil {
		return "", err
	}
	return fmt.Sprintf("user-%d", id), nil
}

func main() {
	ctx := context.Background()
	name, err := fetchUser(ctx, 42)
	fmt.Println(name, err)

	fmt.Println(ctx.Done() == nil)
	_, hasDeadline := ctx.Deadline()
	fmt.Println(hasDeadline)

	fmt.Println(context.TODO())
}
```

輸出：
```text
user-42 <nil>
true
false
context.TODO
```

### WithCancel：手動取消

`WithCancel` 從父 context 衍生出子 context 和一個 `cancel` 函式。呼叫 `cancel` 後，子 context 的 `Done()` 會關閉，所有監聽它的 goroutine 都能收到通知。父 context 被取消時，子 context 也會跟著被取消。

範例的產生器在背景不斷產生數字，主程式拿到 3 之後呼叫 `cancel`，背景 goroutine 就會結束，不會[洩漏](/concurrency-cancellation)。

簽名：
```go
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
```

範例：
```go
package main

import (
	"context"
	"fmt"
)

func generate(ctx context.Context) <-chan int {
	ch := make(chan int)
	go func() {
		defer close(ch)
		for i := 1; ; i++ {
			select {
			case <-ctx.Done():
				return
			case ch <- i:
			}
		}
	}()
	return ch
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())

	for n := range generate(ctx) {
		fmt.Println(n)
		if n == 3 {
			cancel()
			break
		}
	}

	<-ctx.Done()
	fmt.Println(ctx.Err())
}
```

輸出：
```text
1
2
3
context canceled
```

### WithTimeout：限時完成

`WithTimeout` 在指定時間後自動取消，是最常用的形式：呼叫外部服務、查資料庫都應該設上限。逾時後 `Err()` 回傳 `context.DeadlineExceeded`，可用 `errors.Is` 判斷。

簽名：
```go
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
```

範例：
```go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

func slowQuery(ctx context.Context) (string, error) {
	select {
	case <-time.After(time.Second):
		return "result", nil
	case <-ctx.Done():
		return "", ctx.Err()
	}
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer cancel()

	_, err := slowQuery(ctx)
	fmt.Println("error:", err)
	fmt.Println(errors.Is(err, context.DeadlineExceeded))
}
```

輸出：
```text
error: context deadline exceeded
true
```

### WithDeadline：指定截止時刻

`WithDeadline` 和 `WithTimeout` 一樣，只是給「幾點幾分截止」而不是「多久之後」。範例的截止時刻已經過去，所以 context 一建立就已經是取消狀態。

子 context 的截止時間不會比父 context 晚：父 context 9 點截止，子 context 就算設一小時後，實際截止時間仍是 9 點。

簽名：
```go
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
```

範例：
```go
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	deadline := time.Date(2026, time.March, 14, 9, 0, 0, 0, time.UTC)
	ctx, cancel := context.WithDeadline(context.Background(), deadline)
	defer cancel()

	d, ok := ctx.Deadline()
	fmt.Println(d, ok)
	fmt.Println(ctx.Err())

	child, cancelChild := context.WithTimeout(ctx, time.Hour)
	defer cancelChild()
	cd, _ := child.Deadline()
	fmt.Println(cd.Equal(deadline))
}
```

輸出：
```text
2026-03-14 09:00:00 +0000 UTC true
context deadline exceeded
true
```

### WithValue：傳遞請求範圍的值

`WithValue` 把一組鍵值掛在 context 上，往下傳的每一層都能用 `Value` 讀出。適合放「跟著這次請求走」的資料，例如請求 ID、登入使用者。

鍵要用自訂的未匯出型別，避免和其他套件的鍵撞名；通常再包一對存取函式，讓呼叫端不必知道鍵。不要拿它傳可選參數或相依物件，那些應該是明確的函式參數。詳見 [context 值與實務](/context-values-best-practices)。

簽名：
```go
func WithValue(parent Context, key, val any) Context
```

範例：
```go
package main

import (
	"context"
	"fmt"
)

type ctxKey int

const requestIDKey ctxKey = 0

func WithRequestID(ctx context.Context, id string) context.Context {
	return context.WithValue(ctx, requestIDKey, id)
}

func RequestID(ctx context.Context) (string, bool) {
	id, ok := ctx.Value(requestIDKey).(string)
	return id, ok
}

func handle(ctx context.Context) {
	if id, ok := RequestID(ctx); ok {
		fmt.Println("request id:", id)
		return
	}
	fmt.Println("no request id")
}

func main() {
	handle(context.Background())

	ctx := WithRequestID(context.Background(), "req-7f3a")
	handle(ctx)
}
```

輸出：
```text
no request id
request id: req-7f3a
```

### WithCancelCause 與 Cause：記錄取消原因

`Err()` 只能告訴你「被取消了」或「逾時了」。Go 1.20 起，`WithCancelCause` 的 `cancel` 可以帶一個 error 說明原因，事後用 `context.Cause(ctx)` 取出；Go 1.21 起，`WithTimeoutCause`、`WithDeadlineCause` 可以指定逾時時的原因。

`Err()` 的值不變，原有判斷 `context.Canceled` 的程式碼不受影響。

簽名：
```go
func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)
func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)
func Cause(c Context) error
```

範例：
```go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

var errShutdown = errors.New("server shutting down")

func main() {
	ctx, cancel := context.WithCancelCause(context.Background())
	cancel(errShutdown)

	fmt.Println(ctx.Err())
	fmt.Println(context.Cause(ctx))

	tctx, tcancel := context.WithTimeoutCause(context.Background(), 10*time.Millisecond, errors.New("payment API too slow"))
	defer tcancel()
	<-tctx.Done()
	fmt.Println(tctx.Err())
	fmt.Println(context.Cause(tctx))
}
```

輸出：
```text
context canceled
server shutting down
context deadline exceeded
payment API too slow
```

### AfterFunc：取消時執行清理

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

簽名：
```go
func AfterFunc(ctx Context, f func()) (stop func() bool)
```

範例：
```go
package main

import (
	"context"
	"fmt"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())

	done := make(chan struct{})
	context.AfterFunc(ctx, func() {
		fmt.Println("releasing resources")
		close(done)
	})

	other, cancelOther := context.WithCancel(context.Background())
	stop := context.AfterFunc(other, func() {
		fmt.Println("never printed")
	})
	fmt.Println("stopped:", stop())
	cancelOther()

	cancel()
	<-done
	fmt.Println("done")
}
```

輸出：
```text
stopped: true
releasing resources
done
```

### WithoutCancel：切斷取消但保留值

Go 1.21 起，`WithoutCancel` 衍生出一個不會隨父 context 取消的 context，但仍能讀到父 context 的值。用在請求結束後還要繼續做的事，例如寫稽核記錄：請求已經結束、context 被取消了，記錄仍要寫完，而且需要請求 ID。

注意：這樣的 context 沒有截止時間，需要時自己再包一層 `WithTimeout`。

簽名：
```go
func WithoutCancel(parent Context) Context
```

範例：
```go
package main

import (
	"context"
	"fmt"
)

type ctxKey string

func main() {
	parent, cancel := context.WithCancel(context.WithValue(context.Background(), ctxKey("user"), "alice"))
	detached := context.WithoutCancel(parent)

	cancel()

	fmt.Println(parent.Err())
	fmt.Println(detached.Err())
	fmt.Println(detached.Value(ctxKey("user")))
}
```

輸出：
```text
context canceled
<nil>
alice
```

## 重點整理

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

## 資料來源

- [dsxwk/go-docs（標準庫分類架構參考）](https://github.com/dsxwk/go-docs)
- [pkg.go.dev：context](https://pkg.go.dev/context)
- [Go 1.26.0 原始碼：src/context](https://github.com/golang/go/tree/go1.26.0/src/context)
