Go 的 context 是管理请求生命周期、传递取消信号和共享请求级数据的核心机制,具有只读性、树状继承、Done通道通知取消、Value传小量元数据等特性。
在 Go 中,context 是管理请求生命周期、传递取消信号和跨层共享请求级数据(如用户身份、请求 ID、超时控制)的核心机制。它不是“全局变量”,而是随请求流动的、不可变的、线程安全的携带者。
Go 的 context.Context 接口包含四个方法:Deadline()、Done()、Err() 和 Value()。关键点在于:
WithCancel、WithValue),不能直接改写其内容;Done() 返回一个只读 channel,当 context 被取消或超时时自动关闭,协程应监听此 channel 以及时退出;Value(key) 用于传递请求范围的元数据(如用户 ID、token),但仅限小量、低频、非关键业务数据;不推荐传结构体或大对象,更不应传函数或通道。典型场景:中间件从 token 解析出用户 ID 或用户对象,并将其写入 context,后续 handler 和业务层可安全读取。
示例(使用标准 net/http):
func AuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 模拟从 header 解析用户 ID userID := r.Header.Get("X-User-ID") if userID == "" { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } // 将用户 ID 注入 context,使用自定义 key 类型避免字符串冲突 ctx := context.WithValue(r.Context(), userKey{}, userID) next.ServeHTTP(w, r.WithContext(ctx)) }) } // 自定义 key 类型(推荐,防止与其他模块 key 冲突) type userKey struct{} func getUserID(ctx context.Context) string { if uid, ok := ctx.Value(userKey{}).(string); ok { return uid } return "" } // 在 handler 中使用 func profileHandler(w http.ResponseWriter, r *http.Request) { userID := getUserID(r.Context()) fmt.Fprintf(w, "Hello, user %s", userID) }统一管理取消信号与超时控制
对下游调用(如数据库查询、HTTP 外部请求、RPC)必须带上 context,确保上游取消能级联中断所有依赖操作。
context.WithTimeout 或 context.WithDeadline 为每个外部调用设置合理超时;
database/sql)、HTTP client(http.NewRequestWithContext)、gRPC client 均原生支持 context;ctx.Done() 并提前返回。示例(带超时的 HTTP 调用):
func fetchUserInfo(ctx context.Context, userID string) (string, error) { // 为本次调用设置 3 秒超时 ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/users/"+userID, nil) if err != nil { return "", err } resp, err := http.DefaultClient.Do(req) if err != nil { // 如果是 context 被取消或超时,err 通常是 context.Canceled 或 context.DeadlineExceeded return "", err } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) return string(body), nil }最佳实践与常见陷阱
RequestMeta)作为 value,但需确保其不可变性。