Files
toutoukan/controllers/user/userScore.go
2025-09-24 20:56:55 +08:00

58 lines
1.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package user
import (
"database/sql"
"net/http"
"toutoukan/init/databaseInit"
"github.com/gin-gonic/gin"
)
// UserReq 定义了请求中用户ID的结构体
type UserReq struct {
Uid string `json:"uid" binding:"required,min=1,max=50"`
}
func GetScore(c *gin.Context) {
var req UserReq
// 1. 解析并验证请求参数
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "参数解析失败",
"detail": err.Error(),
})
return
}
// 2. 根据 user_id 查询用户总积分
// 使用 sql.NullInt64 来处理 SUM 函数可能返回 NULL 的情况
var totalPoints sql.NullInt64
if err := databaseInit.UserDB.Table("user_points").
Where("user_id = ?", req.Uid).
Select("SUM(points_change)").
Scan(&totalPoints).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "查询用户积分失败: " + err.Error(),
})
return
}
// 3. 返回查询结果
// 检查 totalPoints 是否为 NULL如果是则返回 0
finalPoints := 0
if totalPoints.Valid {
finalPoints = int(totalPoints.Int64)
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "查询成功",
"data": gin.H{
"user_id": req.Uid,
"total_points": finalPoints,
},
})
}