package logic import ( "context" "encoding/json" "healthapi/internal/model" "healthapi/internal/svc" "healthapi/internal/types" "healthapi/pkg/errorx" "github.com/zeromicro/go-zero/core/logx" ) type GetUserProfileLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewGetUserProfileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserProfileLogic { return &GetUserProfileLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *GetUserProfileLogic) GetUserProfile() (resp *types.UserInfo, err error) { // 从 context 获取用户ID(JWT中间件设置) userID, err := GetUserIDFromCtx(l.ctx) if err != nil { return nil, errorx.ErrUnauthorized } var user model.User if err := l.svcCtx.DB.First(&user, userID).Error; err != nil { return nil, errorx.ErrUserNotFound } return &types.UserInfo{ ID: uint(user.ID), Phone: user.Phone, Email: user.Email, Nickname: user.Nickname, Avatar: user.Avatar, SurveyCompleted: user.SurveyCompleted, }, nil } // GetUserIDFromCtx 从上下文获取用户ID func GetUserIDFromCtx(ctx context.Context) (uint, error) { // go-zero JWT 中间件将用户信息存储在 context 中 val := ctx.Value("user_id") if val == nil { return 0, errorx.ErrUnauthorized } // 根据 JWT payload 类型进行转换 switch v := val.(type) { case float64: return uint(v), nil case int64: return uint(v), nil case int: return uint(v), nil case uint: return v, nil case json.Number: id, _ := v.Int64() return uint(id), nil default: return 0, errorx.ErrUnauthorized } }