In a rest api, when the body is set to "{}", the json Decoder will not generate an error. This makes it necessary to check if the target struct is still nil
.
I need to check if the library is supposed to work like this, or if this is an issue with it.
// Client Side this request
req, err := http.NewRequest("POST", "url", strings.NewReader("{}") )
// Curl equivalent:
curl -X POST -d '{}' http://api:8080/r/primitives/multiply
// Server side
type Operands struct {
Values []float64 `json:"Values"`
}
func handler(req *http.Request, res *http.Response) (string, error) {
operands := Operands{}
err := json.NewDecoder(req.Body).Decode(&operands)
if err != nil {
res.StatusCode = 400
res.Status = http.StatusText(res.StatusCode)
http.StatusText(res.StatusCode)
return "", err
}
operands.Values[0] // It will fail here.
}
Edit 1: The decoder works fine with and empty body "" with the error being generated, and works fine with a correct body like this one: {"Values" : [ 5.0 , 2.0 ]}
Edit 2: The issue here is that with a "{}" body, it will not return an error when decoding, instead it will keep the target struct as nil.
{}
is just an empty Json object, and it will decode fine to your Operands
struct, as the struct is not required to have anything in the Operands
array.
You need to validate that yourself, e.g.
err := json.NewDecoder(req.Body).Decode(&operands)
if err != nil || len(operands.Values) == 0{