后端用 gin 写个自用的接口,假设结构体为下面
type Machine struct {
Hostname string `json:"Hostname,omitempty" binding:"required"`
DeviceLabel string `json:"DeviceLabel,omitempty" binding:"required"`
}
POST 接口必要的字段都写了 required 了,但是更新的时候发来的 json 的不一定会是全面的(也就不能用 gin 的 c.BindJson ),所以目前是下面写的
var data models.Machines
if err := json.NewDecoder(c.Request.Body).Decode(&data); err != nil {
c.JSON( http.StatusOK, gin.H{
"status": 1,
"msg": err.Error(),
})
return
}
但是这样我测试了下任何正确的 json 都不会为 nil,例如:
{"asdasd":"asdasfdsf"}
搜了下 beego 的 validation 包也不能达到要求,如何让用户只能传递符合结构体的 json