
以下字段 name, description, maxBandwidthIn 和 maxBandwidthOut 都不是必选的,我希望前端没有传过来的字段在结构体中也可以被忽略。以下是我写的有问题的代码,不知道各位大佬平时都是怎么处理这样的需求呢还望大家多多指教(((蟹蟹~
type UpdateModel struct { Name string `json:"name" binding:"omitempty"` Description string `json:"description" binding:"omitempty"` MaxBandwidthIn int `json:"maxBandwidthIn" binding:"omitempty"` MaxBandwidthOut int `json:"maxBandwidthOut" binding:"omitempty"` } func UpdateItem(context *gin.Context) { var req UpdateModel // 初始化结构体,所有字段赋默认值,binding:"omitempty"不起作用 if err = context.BindJSON(&req); err != nil { context.JSON( http.StatusBadRequest, err.Error()) return } ... } 1 mason961125 2020-10-14 21:20:10 +08:00 |
2 tiedan 2020-10-14 22:30:09 +08:00 字段用指针,判断指针是不是 nil |
3 wleven 2020-10-15 09:27:26 +08:00 `json:"maxBandwidthOut,omitempty" |
4 LotteWong OP |
6 wleven 2020-10-15 10:47:31 +08:00 如果用 gorm 的话入库可以忽略空值 |