1 Star 0 Fork 0

码农兴哥/go-demo-2025

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main2_5.go 1.10 KB
一键复制 编辑 原始数据 按行查看 历史
码农兴哥 提交于 2026-01-15 17:56 +08:00 . demo06_context
package main
import (
"context"
"fmt"
)
// context.WithValue() - 值传递
// 类型安全的key定义(重要!)
type contextKey string
const (
requestIDKey contextKey = "requestID"
userIDKey contextKey = "userID"
authTokenKey contextKey = "authToken"
)
func withValueExample() {
fmt.Println("=== WithValue 示例 ===")
// 创建带值的Context链
ctx := context.Background()
ctx = context.WithValue(ctx, requestIDKey, "req-12345")
ctx = context.WithValue(ctx, userIDKey, "user-67890")
ctx = context.WithValue(ctx, authTokenKey, "token-abcde")
// 传递Context给多个处理函数
processRequest(ctx)
}
func processRequest(ctx context.Context) {
// 从Context中获取值
requestID := ctx.Value(requestIDKey).(string)
userID := ctx.Value(userIDKey).(string)
fmt.Printf("处理请求: requestID=%s, userID=%s\n", requestID, userID)
// 调用子函数
callDatabase(ctx)
}
func callDatabase(ctx context.Context) {
// 在调用链中传递Context
authToken := ctx.Value(authTokenKey).(string)
fmt.Printf("数据库调用使用token: %s\n", authToken)
}
func main() {
withValueExample()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/rxbook/go-demo-2025.git
git@gitee.com:rxbook/go-demo-2025.git
rxbook
go-demo-2025
go-demo-2025
master

搜索帮助