gin內置驗證器使用
func TopicUrl(f1 validator.FieldLevel) bool {
return true //返回true表示驗證成功
}
func main(){
router:=gin.Default()
if v, ok := binding.Validator.Engine().(*validator.Validate); ok { //類型斷言
v.RegisterValidation("topicurl", TopicUrl) //注冊調用tag和自定義驗證器
}
v1:=router.Group("/v1/topics")
{
v1.GET("/:topic_id",GetTopicDetail)
}
}
type Topic struct {
TopicID int `form:"id" json:"id"`
TopicTitle string `form:"title" json:"title" binding:"min=4,max=20"` //長度4到20之間
TopicShortTitle string `form:"stitle" json:"stitle" binding:"required,nefield=ToipcTitle"`//required非空,nfield不能等於TopicTitle字段
UserIP string `form:"ip" json:"ip" binding:"ipv4"`
TopicScore int `form:"score" json:"score" binding:"omitempty,gt=5"` //omitempty要么不傳,傳的話就要大於5
}
type Topic struct {
TopicID int `form:"id" json:"id"`
TopicTitle string `form:"title" json:"title" binding:"min=4,max=20"`
TopicShortTitle string `form:"stitle" json:"stitle" binding:"required,nefield=TopicTitle"`
UserIP string `form:"ip" json:"ip" binding:"ipv4"`
TopicScore int `form:"score" json:"score" binding:"omitempty,gt=5"`
TopicUrl string `form:"url" json:"url" binding:"topicurl"` //綁定自定義的topicurl驗證器
}
type Topics struct {
TopicList [] *Topic `form:"topiclist" json:"topiclist" binding:"gt=0,lt=3,dive"` //dive表示進入列表或數組里面的字段去驗證,這里是驗證上面的Topic,dive要寫在后面,不然如果lt寫在dive后面就是驗證里面的數據的lt>3,而不是列表的lt>3
Size int `form:"size" json:"size"`
}