Param error message generate
This commit is contained in:
parent
6539ae20fa
commit
6ba4d1ae82
3 changed files with 44 additions and 10 deletions
|
@ -3,20 +3,43 @@ package controllers
|
|||
import (
|
||||
"Cloudreve/serializer"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"gopkg.in/go-playground/validator.v8"
|
||||
)
|
||||
|
||||
// ParamErrorMsg 根据Validator返回的错误信息给出错误提示
|
||||
func ParamErrorMsg(filed string, tag string) string {
|
||||
// 未通过验证的表单域与中文对应
|
||||
fieldMap := map[string]string{
|
||||
"UserName": "用户名",
|
||||
"Password": "密码",
|
||||
}
|
||||
// 未通过的规则与中文对应
|
||||
tagMap := map[string]string{
|
||||
"required": "不能为空",
|
||||
"min": "太短",
|
||||
"max": "太长",
|
||||
}
|
||||
fieldVal, findField := fieldMap[filed]
|
||||
tagVal, findTag := tagMap[tag]
|
||||
if findField && findTag {
|
||||
// 返回拼接出来的错误信息
|
||||
return fieldVal + tagVal
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ErrorResponse 返回错误消息
|
||||
func ErrorResponse(err error) serializer.Response {
|
||||
// 处理 Validator 产生的错误
|
||||
if ve, ok := err.(validator.ValidationErrors); ok {
|
||||
for _, e := range ve {
|
||||
return serializer.ParamErr(
|
||||
fmt.Sprintf("%s %s", e.Field, e.Tag),
|
||||
ParamErrorMsg(e.Field, e.Tag),
|
||||
err,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := err.(*json.UnmarshalTypeError); ok {
|
||||
return serializer.ParamErr("JSON类型不匹配", err)
|
||||
}
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
package controllers
|
||||
|
||||
import (
|
||||
"Cloudreve/serializer"
|
||||
"Cloudreve/service/user"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
@ -10,11 +9,8 @@ import (
|
|||
func UserLogin(c *gin.Context) {
|
||||
var service service.UserLoginService
|
||||
if err := c.ShouldBindJSON(&service); err == nil {
|
||||
//res := service.Login(c)
|
||||
c.JSON(200, serializer.Response{
|
||||
Code: 0,
|
||||
Msg: "OK",
|
||||
})
|
||||
res := service.Login(c)
|
||||
c.JSON(200, res)
|
||||
} else {
|
||||
c.JSON(200, ErrorResponse(err))
|
||||
}
|
||||
|
|
|
@ -1,7 +1,22 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"Cloudreve/serializer"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// UserLoginService 管理用户登录的服务
|
||||
type UserLoginService struct {
|
||||
UserName string `form:"user_name" json:"user_name" binding:"required,min=5,max=30"`
|
||||
Password string `form:"password" json:"password" binding:"required,min=8,max=40"`
|
||||
//TODO 细致调整验证规则
|
||||
UserName string `form:"userName" json:"userName" binding:"required,min=5,max=30"`
|
||||
Password string `form:"Password" json:"Password" binding:"required,min=8,max=40"`
|
||||
CaptchaCode string `form:"captchaCode" json:"captchaCode"`
|
||||
}
|
||||
|
||||
// Login 用户登录函数
|
||||
func (service *UserLoginService) Login(c *gin.Context) serializer.Response {
|
||||
return serializer.Response{
|
||||
Code: 0,
|
||||
Msg: "OK",
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue