2017-04-20 22:40:52 +00:00
|
|
|
// Copyright 2017 Vector Creations Ltd
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
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 {
|
|
|
|
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{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
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
|
|
|
|
}
|
2017-03-10 16:50:41 +00:00
|
|
|
|
|
|
|
// LogThenError logs the given error then returns a matrix-compliant 500 internal server error response.
|
|
|
|
// This should be used to log fatal errors which require investigation. It should not be used
|
|
|
|
// to log client validation errors, etc.
|
|
|
|
func LogThenError(req *http.Request, err error) util.JSONResponse {
|
|
|
|
util.GetLogger(req.Context()).WithError(err).Error("request failed")
|
|
|
|
return jsonerror.InternalServerError()
|
|
|
|
}
|