自定义校验
在字段使用自定义的校验
案例: Currency使用自定义的货币类型, 为了后续的扩展, 直接硬编码不方便还容易出问题
type CreateTransferRequest struct {
FromAccountID int64 `json:"fromAccountID" binding:"required"`
ToAccountID int64 `json:"toAccountID" binding:"required"`
Amount int64 `json:"amount" binding:"required"`
Currency string `json:"currency" binding:"required,currency"`
}
使用gin的校验
go get github.com/go-playground/validator/v10
编写自定义的校验规则, 以bool为返回值
// 定义货币类型
const (
CNY = "CNY"
USD = "USD"
EDR = "EDR"
)
// 校验传入的参数 是否为其一
func validateCurrency(fl validate.FieldLabel) bool {
// fl使用go映射, 需要转出需要的字段类型
currency, ok := fl.Fileld().Interface().(string)
switch currency {
case CNY,USD.EDR:
return true
}
return false
}
gin中使用: 参考案例: https://liuqh.icu/2021/05/30/go/gin/11-validate/
func main(){
gin.Default()
if validate, ok := binding.Validator.Engine().(valitor.Validate); ok {
validate.RegisterValidation("currency", validateCurrency)
}
}