1

I do have this struct for my request

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

If I don't send the "forklift_id" in the json request body, the unmarshalling assigns "" without returning error, I wonder if there is something like

`json: "forklift_id,notempty"`

so the unmarshalling returns an error if the field is not present or empty.

Thanks in advance

Migdress
  • 138
  • 1
  • 12
  • Not declare `omitempty` means "notempty", if you expect the "forklift_id" is not empty string, you can define as `ForkliftID *string json:"forklift_id"`, the default value of point is nil – beiping96 Jul 05 '19 at 03:39
  • I did that, but there is no error if the field is not present, so I want to know if there is an explicit metadata to cause an error if the field is not present – Migdress Jul 05 '19 at 17:17

2 Answers2

4

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")
}
novalagung
  • 9,699
  • 2
  • 50
  • 74
3

Change the field type to *String. After unmarshaling, if the value is nil, then you know the JSON field was not provided.

See here for a more thorough example of unmarshaling error-checking.

colm.anseo
  • 14,462
  • 3
  • 33
  • 44