Re-migrate code
This commit is contained in:
@@ -2,12 +2,52 @@ 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) {
|
||||
@@ -35,8 +75,7 @@ func GetCurrentUser(ctx *gin.Context) (models.User, bool) {
|
||||
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(),
|
||||
"message": "提交数据格式不正确",
|
||||
})
|
||||
return false
|
||||
}
|
||||
@@ -48,8 +87,7 @@ func BindJSON(ctx *gin.Context, obj interface{}) bool {
|
||||
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(),
|
||||
"message": "查询参数不正确",
|
||||
})
|
||||
return false
|
||||
}
|
||||
@@ -58,11 +96,12 @@ func BindQuery(ctx *gin.Context, obj interface{}) bool {
|
||||
|
||||
// ErrorResponse 返回错误响应
|
||||
func ErrorResponse(ctx *gin.Context, status int, message string, err ...error) {
|
||||
friendly := friendlyMessage(message)
|
||||
response := gin.H{
|
||||
"message": message,
|
||||
"message": friendly,
|
||||
}
|
||||
if len(err) > 0 && err[0] != nil {
|
||||
response["error"] = err[0].Error()
|
||||
response["error"] = friendlyMessage(err[0].Error())
|
||||
}
|
||||
ctx.JSON(status, response)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user