2017-03-10 11:32:53 +00:00
|
|
|
package httputil
|
2017-03-07 16:11:08 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2017-03-09 11:47:06 +00:00
|
|
|
"net/http"
|
|
|
|
|
2017-03-07 16:11:08 +00:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/jsonerror"
|
|
|
|
"github.com/matrix-org/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
// UnmarshalJSONRequest into the given interface pointer. Returns an error JSON response if
|
|
|
|
// there was a problem unmarshalling. Calling this function consumes the request body.
|
|
|
|
func UnmarshalJSONRequest(req *http.Request, iface interface{}) *util.JSONResponse {
|
|
|
|
defer req.Body.Close()
|
|
|
|
if err := json.NewDecoder(req.Body).Decode(iface); err != nil {
|
2017-03-09 11:47:06 +00:00
|
|
|
// TODO: We may want to suppress the Error() return in production? It's useful when
|
|
|
|
// debugging because an error will be produced for both invalid/malformed JSON AND
|
|
|
|
// valid JSON with incorrect types for values.
|
2017-03-07 16:11:08 +00:00
|
|
|
return &util.JSONResponse{
|
|
|
|
Code: 400,
|
2017-03-09 11:47:06 +00:00
|
|
|
JSON: jsonerror.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()),
|
2017-03-07 16:11:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|