validator庫在gin中的使用

HaimaBlog發表於2024-05-08

目錄
  • 封裝語言包翻譯器
  • tag中設定驗證規則
  • 控制層驗
  • curl請求
  • 返回結果

封裝語言包翻譯器

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

相關文章