Cloudreve/routers/controllers/main.go

67 lines
1.6 KiB
Go
Raw Normal View History

2019-11-05 06:49:56 -05:00
package controllers
import (
"encoding/json"
model "github.com/cloudreve/Cloudreve/v3/models"
"github.com/cloudreve/Cloudreve/v3/pkg/serializer"
2019-11-12 02:34:54 -05:00
"github.com/gin-gonic/gin"
2020-03-09 01:07:36 -05:00
"gopkg.in/go-playground/validator.v9"
2019-11-05 06:49:56 -05:00
)
2019-11-06 03:42:13 -05:00
// ParamErrorMsg 根据Validator返回的错误信息给出错误提示
func ParamErrorMsg(filed string, tag string) string {
// 未通过验证的表单域与中文对应
fieldMap := map[string]string{
2019-11-11 06:13:17 -05:00
"UserName": "邮箱",
2019-11-06 03:42:13 -05:00
"Password": "密码",
2019-11-16 00:37:42 -05:00
"Path": "路径",
2020-01-26 00:07:05 -05:00
"SourceID": "原始资源",
2020-02-04 02:29:52 -05:00
"URL": "链接",
2020-02-19 03:05:54 -05:00
"Nick": "昵称",
2019-11-06 03:42:13 -05:00
}
// 未通过的规则与中文对应
tagMap := map[string]string{
"required": "不能为空",
"min": "太短",
"max": "太长",
2019-11-11 06:13:17 -05:00
"email": "格式不正确",
2019-11-06 03:42:13 -05:00
}
fieldVal, findField := fieldMap[filed]
tagVal, findTag := tagMap[tag]
if findField && findTag {
// 返回拼接出来的错误信息
return fieldVal + tagVal
}
return ""
}
2019-11-05 06:49:56 -05:00
// ErrorResponse 返回错误消息
func ErrorResponse(err error) serializer.Response {
2019-11-06 03:42:13 -05:00
// 处理 Validator 产生的错误
2019-11-05 06:49:56 -05:00
if ve, ok := err.(validator.ValidationErrors); ok {
for _, e := range ve {
return serializer.ParamErr(
2020-03-09 01:07:36 -05:00
ParamErrorMsg(e.Field(), e.Tag()),
2019-11-05 06:49:56 -05:00
err,
)
}
}
2019-11-06 03:42:13 -05:00
2019-11-05 06:49:56 -05:00
if _, ok := err.(*json.UnmarshalTypeError); ok {
return serializer.ParamErr("JSON类型不匹配", err)
}
return serializer.ParamErr("参数错误", err)
}
2019-11-12 02:34:54 -05:00
// CurrentUser 获取当前用户
func CurrentUser(c *gin.Context) *model.User {
if user, _ := c.Get("user"); user != nil {
if u, ok := user.(*model.User); ok {
return u
}
}
return nil
}