目录
封装语言包翻译器
golang
package validator
import (
"fmt"
"net/http"
"reflect"
"github.com/go-playground/locales/zh_Hans_CN"
unTrans "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
zhTrans "github.com/go-playground/validator/v10/translations/zh"
)
func Validate(data interface{}) (string, int) {
validate := validator.New()
uni := unTrans.New(zh_Hans_CN.New())
trans, _ := uni.GetTranslator("zh_Hans_CN")
err := zhTrans.RegisterDefaultTranslations(validate, trans)
if err != nil {
fmt.Println("err:", err)
}
validate.RegisterTagNameFunc(func(field reflect.StructField) string {
label := field.Tag.Get("label")
return label
})
err = validate.Struct(data)
if err != nil {
for _, v := range err.(validator.ValidationErrors) {
return v.Translate(trans), http.StatusUnprocessableEntity
}
}
return "", 0
}
tag中设置验证规则
validate:定义验证规则
lable:自定义错误提示
golang
// DealerUserAddress 结构体
type UserAddress struct {
global.GVA_MODEL
Address string `json:"address" form:"address" validate:"required" label:"地址" gorm:"column:address;comment:地址;size:1000;default:'';"` //地址
ContactPerson string `json:"contactPerson" form:"contactPerson" validate:"required" label:"联系人" gorm:"column:contact_person;comment:联系人;size:255;default:'';"` //联系人
Mobile string `json:"mobile" form:"mobile" validate:"required,min=11" label:"手机号" gorm:"column:mobile;comment:手机号;size:12;default:'';"` //手机号
ManuId int `json:"manuId" form:"manuId" gorm:"column:manu_id;comment:经销商ID;"` //经销商ID
Mark string `json:"mark" form:"mark" gorm:"column:mark;comment:注意;size:1000;default:'';"`
global.GVA_DATA_AUTH_MODEL
}
更多验证规则参考手册
https://github.com/go-playground/validator
控制层验
golang
func (userAddressApi *UserAddressApi) CreateDealerUserAddress(c *gin.Context) {
userToken, _, e := common.GetContextDealerUser(c)
if e != nil {
response.FailWithMessage("获取用户信息失败", c)
return
}
var userAddressApi erp.UserAddress
err := c.ShouldBindJSON(&userAddressApi)
if err != nil {
global.GVA_LOG.Error("参数解析失败!", zap.Error(err))
response.FailWithMessage("参数解析失败", c)
return
}
if msg, errCode := validator.Validate(userAddressApi); errCode != 0 {
err := fmt.Errorf("参数验证失败!code:%d msg:%s", errCode, msg)
global.GVA_LOG.Error(err.Error(), zap.Error(err))
response.FailWithMessage(err.Error(), c)
return
}
if err := userAddressService.CreateUserAddress(&userAddressApi, userToken); err != nil {
global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithDetailed(userAddressApi, "创建成功", c)
}
}
curl请求
shell
curl --location --request POST 'http://127.0.0.1:8889/dealerClientErp/createDealerClient' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--header 'Accept: */*' \
--header 'Host: 127.0.0.1:8889' \
--header 'Connection: keep-alive' \
--data-raw '{
"username": "haima1",
"mobile": "",
"clientType": 3,
"mark": "this is test"
}'
返回结果
json
{
"code": 7,
"data": {},
"msg": "参数验证失败!code:422 msg:手机号为必填字段"
}
参考文章:
https://www.liwenzhou.com/posts/Go/validator-usages/#c-1-0-2