first commit
This commit is contained in:
25
common/ctxdata/ctxData.go
Normal file
25
common/ctxdata/ctxData.go
Normal file
@@ -0,0 +1,25 @@
|
||||
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 {
|
||||
return 0, fmt.Errorf("用户 ID 转换失败: %+v", err)
|
||||
}
|
||||
|
||||
return uid, nil
|
||||
}
|
||||
Reference in New Issue
Block a user