wz-golang-server/server/modules/user/controller/user_profile_controller.go

75 lines
2.1 KiB
Go

// Package controller 控制器层
package controller
import (
"context"
"encoding/json"
"strconv"
"strings"
"server/common"
"server/config"
"server/modules/user/service"
"server/modules/user/vo"
"github.com/gin-gonic/gin"
)
type UserProfileController struct {
service *service.UserService
}
func NewUserProfileController() *UserProfileController {
return &UserProfileController{service: service.NewUserService()}
}
func (ctrl *UserProfileController) RegisterRoutes(r *gin.RouterGroup) {
group := r.Group("/user")
group.GET("/profile", ctrl.GetProfile)
}
// GetProfile 获取登录用户信息
// @Summary 获取登录用户信息
// @Tags 用户
// @Param platformType query int false "平台类型(默认1-微信小程序)"
// @Success 200 {object} common.Response
// @Router /user/profile [get]
func (ctrl *UserProfileController) GetProfile(c *gin.Context) {
loginUser := common.GetLoginUser(c)
if loginUser == nil || loginUser.ID == "" {
common.Error(c, 401, "未登录")
return
}
userID, err := strconv.ParseInt(loginUser.ID, 10, 64)
if err != nil {
common.Error(c, 400, "用户ID格式错误")
return
}
platformType, _ := strconv.ParseInt(c.DefaultQuery("platformType", "1"), 10, 8)
cacheKey := common.RedisConst.UserProfile.Prefix + strconv.FormatInt(userID, 10) + ":" + strconv.FormatInt(platformType, 10)
if config.RDB != nil {
cacheData, err := config.RDB.Get(context.Background(), cacheKey).Result()
if err == nil && strings.TrimSpace(cacheData) != "" {
var cachedProfile vo.UserProfileVO
if err := json.Unmarshal([]byte(cacheData), &cachedProfile); err == nil {
config.RDB.Expire(context.Background(), cacheKey, common.RedisConst.UserProfile.Expire)
common.Success(c, cachedProfile)
return
}
}
}
profile, err := ctrl.service.GetProfile(userID, int8(platformType))
if err != nil {
common.Error(c, 500, err.Error())
return
}
if config.RDB != nil {
if data, err := json.Marshal(profile); err == nil {
_ = config.RDB.Set(context.Background(), cacheKey, data, common.RedisConst.UserProfile.Expire).Err()
}
}
common.Success(c, profile)
}