将JSON解组到结构时如何不允许空字段

时间:2019-07-05 02:50:49

标签: json go

我确实有此结构可用于我的请求

// This will allow blade to create the url with placeholders in PHP, and it will be interpreted 
// as a string literal in JS and assigned to the variable placeholderUrl
var placeholderUrl = "{{ url('api/img', ['foldername', 'filename']) }}";

// Then you can use JS to replace the value in the url
var realUrl = placeholderUrl.replace('filename', data.img);

// Then use the real URL to create the img tag. Notice the alternating single and double quotes
var imgTag = '<img id="pic" src="' + realUrl + '" style="width:500; height:500" />';

// And finally, use the img tag when you add the row
var newRow = $datatable.row.add([data.id, data.name, imgTag]).draw().node();

如果我没有在json请求正文中发送type RequestBody struct { ForkliftID string `json:"forklift_id"` WarehouseID string `json:"warehouse_id,omitempty"` TaskID string `json:"task_id"` } ,则解组将分配“”而不返回错误,我想知道是否存在

"forklift_id"

因此,如果该字段不存在或为空,则解组将返回错误。

预先感谢

2 个答案:

答案 0 :(得分:1)

将字段类型更改为*String。取消编组后,如果值为nil,则说明未提供JSON字段。

有关解封错误检查的更详尽示例,请参见here

答案 1 :(得分:1)

我假设您所做的操作(将有效负载中的空值作为错误处理)是出于http请求有效负载验证的目的。然后,我认为您可以使用@colminator答案,或尝试使用为此特定情况设计的第三方库,例如https://github.com/go-playground/validator

用法示例:

type RequestBody struct {
    ForkliftID  string `json:"forklift_id"  validate:"required"`
    WarehouseID string `json:"warehouse_id" validate:"required"`
    TaskID      string `json:"task_id"`
}

// ...

var payload RequestBody 

// ...

validate := validator.New()
err := validate.Struct(payload)
if err != nil {
    // handle the error
}

带有标签validate:"required"的字段将在validate.Struct()调用期间进行验证。除了required以外,还有许多有用的验证规则。

有关更多详细示例,请查看the example source code


另一种替代解决方案是通过对那些结构的字段进行显式检查。示例:

// ...

if payload.ForkliftID == "" {
     err = fmt.Errorf("Forklift ID cannot be empty")
}
if payload.WarehouseID == "" {
     err = fmt.Errorf("Warehouse ID cannot be empty")
}