I assume what you did (treating empty value from payload as an error) is for validation purposes. If so, I think you can go with @colminator answer, or try to use 3rd party library that designed to solve this particular problem. One example library is 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
}
The field with tag validate:"required"
will be validated when validate.Struct()
called.
There are also a lot of useful validation rules available other than required
.
For a more detailed example, take a look at the example source code
Another alternative solution would be, by performing explicit checks across those struct's fields. Example:
// ...
if payload.ForkliftID == "" {
err = fmt.Errorf("Forklift ID cannot be empty")
}
if payload.WarehouseID == "" {
err = fmt.Errorf("Warehouse ID cannot be empty")
}