golang binding tag
生活随笔
收集整理的這篇文章主要介紹了
golang binding tag
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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>3Size int `form:"size" json:"size"`Age int `form:"age" json:"age" binding:"required,oneof=1 2 3"` //age只能是1 2 3中一個
}
總結
以上是生活随笔為你收集整理的golang binding tag的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript数据类型 - Und
- 下一篇: 【EXLIBRIS】#小词旮旯# 003