tag中的一些用法我也是经常忘记,在这里总结一下。
例子1
type PresignPara struct {Type string `json:"type" form:"type"`UUID string `json:"uuid" form:"uuid"`Name string `json:"name" form:"name"`FileSize int `json:"fileSize" form:"fileSize"`}// json和form,这两个tag是最常见的了,经常用于处理http请求中application/json和form-data
例子2
type user struct {Name string `json:"name" binding:"required"`Email string `json:"email" binding:"required,email"`Address string `json:"email" binding:""`}// 这个就是常见binding校验,Name的校验要求json中name是必传的,Email中要求这个字段也是必传的,而且还必须为“email”// address这个字段没有强制设置binding
例子3
// 还有两种比较常见的使用方式,那就是在json中使用tag "-" 和 “omitempty”// tag ""type Product struct {Name string `json:"name"`ProductID int64 `json:"-"` // 表示不进行序列化或者反序列化Number int `json:"number"`Price float64 `json:"price"`IsOnSale bool `json:"is_on_sale,string"`}// 序列化过后,可以看见{"name":"Xiao mi 6","number":10000,"price":2499,"is_on_sale":"false"}
//omitempty,tag里面加上omitempy,可以在序列化的时候忽略0值或者空值, 这点很重要,我前面的理解一直有问题// Product _type Product struct {Name string `json:"name"`ProductID int64 `json:"product_id,omitempty"`Number int `json:"number"`Price float64 `json:"price"`IsOnSale bool `json:"is_on_sale,omitempty"`}func main() {p := &Product{}p.Name = "Xiao mi 6"p.IsOnSale = falsep.Number = 10000p.Price = 2499.00p.ProductID = 0data, _ := json.Marshal(p)fmt.Println(string(data))}// {"name":"Xiao mi 6","number":10000,"price":2499}
例子4
//gorm中的tag,待补充
