qnc-server-tob/common/ctxdata/ctxData.go

26 lines
549 B
Go
Raw Normal View History

2025-01-10 00:09:25 +08:00
package ctxdata
import (
"context"
"encoding/json"
"fmt"
)
const CtxKeyJwtUserId = "userId"
// GetUidFromCtx 从 context 中获取用户 ID
func GetUidFromCtx(ctx context.Context) (int64, error) {
// 尝试从上下文中获取 jwtUserId
jsonUid, ok := ctx.Value(CtxKeyJwtUserId).(json.Number)
if !ok {
return 0, fmt.Errorf("无法获取用户 ID, CtxKeyJwtUserId = %v", CtxKeyJwtUserId)
}
// 转换为 int64
uid, err := jsonUid.Int64()
if err != nil {
2025-03-07 03:48:59 +08:00
return 0, fmt.Errorf("用户 ID 转换失败: %v", err)
2025-01-10 00:09:25 +08:00
}
return uid, nil
}