代码拉取完成,页面将自动刷新
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()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。