82 lines
1.8 KiB
Go
82 lines
1.8 KiB
Go
package controllers
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"git.beifan.cn/trace-system/backend-go/models"
|
|
)
|
|
|
|
// GetCurrentUser 从上下文中获取当前用户
|
|
// 如果用户未认证,返回 false 并返回 401 错误
|
|
func GetCurrentUser(ctx *gin.Context) (models.User, bool) {
|
|
user, exists := ctx.Get("user")
|
|
if !exists {
|
|
ctx.JSON(http.StatusUnauthorized, gin.H{
|
|
"message": "未认证",
|
|
})
|
|
return models.User{}, false
|
|
}
|
|
|
|
userModel, ok := user.(models.User)
|
|
if !ok {
|
|
ctx.JSON(http.StatusUnauthorized, gin.H{
|
|
"message": "用户信息无效",
|
|
})
|
|
return models.User{}, false
|
|
}
|
|
|
|
return userModel, true
|
|
}
|
|
|
|
// BindJSON 绑定 JSON 请求体
|
|
// 如果解析失败,返回错误并返回 400 响应
|
|
func BindJSON(ctx *gin.Context, obj interface{}) bool {
|
|
if err := ctx.ShouldBindJSON(obj); err != nil {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{
|
|
"message": "无效的请求数据",
|
|
"error": err.Error(),
|
|
})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// BindQuery 绑定查询参数
|
|
// 如果解析失败,返回错误并返回 400 响应
|
|
func BindQuery(ctx *gin.Context, obj interface{}) bool {
|
|
if err := ctx.ShouldBindQuery(obj); err != nil {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{
|
|
"message": "无效的查询参数",
|
|
"error": err.Error(),
|
|
})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// ErrorResponse 返回错误响应
|
|
func ErrorResponse(ctx *gin.Context, status int, message string, err ...error) {
|
|
response := gin.H{
|
|
"message": message,
|
|
}
|
|
if len(err) > 0 && err[0] != nil {
|
|
response["error"] = err[0].Error()
|
|
}
|
|
ctx.JSON(status, response)
|
|
}
|
|
|
|
// SuccessResponse 返回成功响应
|
|
func SuccessResponse(ctx *gin.Context, message string, data ...gin.H) {
|
|
response := gin.H{
|
|
"message": message,
|
|
}
|
|
if len(data) > 0 {
|
|
for key, value := range data[0] {
|
|
response[key] = value
|
|
}
|
|
}
|
|
ctx.JSON(http.StatusOK, response)
|
|
}
|