package controllers import ( "net/http" "strings" "github.com/gin-gonic/gin" "git.beifan.cn/trace-system/backend-go/models" ) func friendlyMessage(message string) string { if message == "" { return "请求失败,请稍后重试" } msg := strings.TrimSpace(message) friendlyMap := []struct { key string val string }{ {"用户名或密码错误", "用户名或密码不正确"}, {"当前密码错误", "当前密码不正确"}, {"令牌生成失败", "登录失败,请稍后重试"}, {"未认证", "请先登录"}, {"用户信息无效", "登录状态无效,请重新登录"}, {"序列号不存在", "序列号不存在"}, {"企业不存在", "企业不存在"}, {"序列号已过期", "序列号已过期"}, {"序列号已被禁用", "序列号已禁用"}, {"序列号已被吊销", "序列号已吊销"}, {"企业名称已存在", "企业名称已存在"}, {"无效的请求数据", "提交数据格式不正确"}, {"无效的查询参数", "查询参数不正确"}, } for _, item := range friendlyMap { if strings.Contains(msg, item.key) { return item.val } } if strings.Contains(msg, "record not found") { return "数据不存在" } return msg } // 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": "提交数据格式不正确", }) 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": "查询参数不正确", }) return false } return true } // ErrorResponse 返回错误响应 func ErrorResponse(ctx *gin.Context, status int, message string, err ...error) { friendly := friendlyMessage(message) response := gin.H{ "message": friendly, } if len(err) > 0 && err[0] != nil { response["error"] = friendlyMessage(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) }