上下文
上下文键
xCtx 包定义的上下文键常量
上下文键
xCtx 包定义了用于在上下文中存储和获取数据的键常量。
import xCtx "github.com/bamboo-services/bamboo-base-go/defined/context"ContextKey 类型
type ContextKey string
func (s ContextKey) String() string {
return string(s)
}预定义键
const (
Nil ContextKey = "" // 空值
Exec ContextKey = "special_execution" // 特殊执行
RequestKey ContextKey = "context_request_key" // 请求唯一标识
ErrorCodeKey ContextKey = "context_error_code" // 错误码
ErrorMessageKey ContextKey = "context_error_message" // 错误描述
UserStartTimeKey ContextKey = "context_user_start_time" // 请求开始时间
DatabaseKey ContextKey = "context_database" // 数据库客户端
RedisClientKey ContextKey = "context_redis_client" // Redis 客户端
SnowflakeNodeKey ContextKey = "context_snowflake_node" // 雪花算法节点
)键说明
字段
类型
使用方式
节点化注入(推荐)
在 Register 时通过节点注入资源:
import (
"context"
xCtx "github.com/bamboo-services/bamboo-base-go/defined/context"
xReg "github.com/bamboo-services/bamboo-base-go/major/register"
xRegNode "github.com/bamboo-services/bamboo-base-go/major/register/node"
)
// 注册时注入数据库和 Redis
reg := xReg.Register(context.Background(), []xRegNode.RegNodeList{
{Key: xCtx.DatabaseKey, Node: initDatabase},
{Key: xCtx.RedisClientKey, Node: initRedis},
})
// 初始化节点函数
func initDatabase(ctx context.Context) (any, error) {
db, err := gorm.Open(...)
return db, err
}从上下文获取值
使用 xCtxUtil 工具函数获取注入的资源:
import xCtxUtil "github.com/bamboo-services/bamboo-base-go/common/utility/context"
func MyHandler(c *gin.Context) {
// 获取标准上下文
ctx := c.Request.Context()
// 获取数据库连接
db := xCtxUtil.MustGetDB(ctx)
// 获取 Redis 客户端
rdb := xCtxUtil.MustGetRDB(ctx)
// 获取雪花算法节点
node := xCtxUtil.GetSnowflakeNode(ctx)
}直接从上下文获取
也可以直接使用 context.Value 获取:
import xCtx "github.com/bamboo-services/bamboo-base-go/defined/context"
func MyHandler(c *gin.Context) {
ctx := c.Request.Context()
// 直接获取并类型断言
if value := ctx.Value(xCtx.DatabaseKey); value != nil {
db := value.(*gorm.DB)
}
}注入时机
| 键 | 注入位置 | 说明 |
|---|---|---|
RequestKey | xHelper.RequestContext() | 框架自动注入 |
UserStartTimeKey | xHelper.RequestContext() | 框架自动注入 |
SnowflakeNodeKey | xReg.Register() 内置节点 | 框架自动注入 |
DatabaseKey | 自定义初始化节点 | 需手动注入 |
RedisClientKey | 自定义初始化节点 | 需手动注入 |
ErrorCodeKey | 错误处理中间件 | 错误时自动设置 |
ErrorMessageKey | 错误处理中间件 | 错误时自动设置 |
上下文流转
Register(ctx, nodeList)
│
├── 内置节点注入 SnowflakeNodeKey
│
├── 自定义节点注入 DatabaseKey, RedisClientKey, ...
│
└── engineInit()
│
└── injectContext(ctx) 中间件
│
└── 每个 HTTP 请求
│
└── c.Request.Context() 包含所有注入的资源