26 lines
550 B
Go
26 lines
550 B
Go
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
|
|
}
|