validator库在gin中的使用

封装语言包翻译器

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:自定义错误提示

// UserAddress 结构体
type UserAddress struct {
	global.GVA_MODEL
	Address       string `json:"address" form:"address"  validate:"required,min=1,max=160" label:"地址" gorm:"column:address;comment:地址;size:1000;default:'';"` //地址
	State         int    `json:"state" validate:"required,oneof=1 2" label:"状态 1:显示 2:隐藏"`
	ContactPerson string `json:"contactPerson" form:"contactPerson" validate:"required" label:"联系人" gorm:"column:contact_person;comment:联系人;size:255;default:'';"` //联系人
	Full          bool   `json:"full" form:"full" validate:"omitempty,oneof=true false" lable:"是否查询全部"`
	Mobile        string `json:"mobile" form:"mobile"  validate:"required,min=11" label:"手机号" gorm:"column:mobile;comment:手机号;size:12;default:'';"` //手机号
	Email         string `json:"email"  validate:"required,email" label:"邮箱"`
	ProtocolIds   []int  `form:"protocolIds[]" search:"-" validate:"omitempty,len=1" label:"协议ids" comment:"协议ids"`
	ExportType    string `form:"exportType" search:"-" validate:"omitempty,oneof=csv xlsx" label:"导出类型 :csv(默认) / xlsx"`
	ManuId        int    `json:"manuId" form:"manuId" gorm:"column:manu_id;comment:经销商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

控制层验

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请求

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"
}'

返回结果

{
    "code": 7,
    "data": {},
    "msg": "参数验证失败!code:422 msg:手机号为必填字段"
}

参考文章:
https://www.liwenzhou.com/posts/Go/validator-usages/#c-1-0-2

热门相关:秦吏   极品仙师   妖魔哪里走   我真是非洲酋长   原来你喜欢我呀