tempestas

A REST API for processing sensor.community data
git clone https://git.bracken.jp/tempestas.git
Log | Files | Refs | README | LICENSE

commit 40fda0087b62c8a91923fa5615b51ebe691e0e67
parent 7de0142e927605acb0227590f756efa0ecd285d7
Author: Chris Bracken <chris@bracken.jp>
Date:   Fri, 12 Nov 2021 10:22:19 -0800

Extract HTTP response writing helper

Extracts a more general HTTP response writing function that can be used
for writing byte data (such as JSON). Refactor errorResponse, which
simply writes a JSON status message to the response body, to delegate
to this function.

Diffstat:
Mhttp/http.go | 16+++++++++-------
1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/http/http.go b/http/http.go @@ -68,17 +68,19 @@ func (s HttpServer) QueryReadings(w http.ResponseWriter, r *http.Request) { return } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - jsonResp, _ := json.Marshal(readings) - w.Write(jsonResp) + resp, _ := json.Marshal(readings) + writeResponse(w, resp, http.StatusOK) } func errorResponse(w http.ResponseWriter, message string, httpStatusCode int) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(httpStatusCode) resp := make(map[string]string) resp["message"] = message jsonResp, _ := json.Marshal(resp) - w.Write(jsonResp) + writeResponse(w, jsonResp, httpStatusCode) +} + +func writeResponse(w http.ResponseWriter, resp []byte, httpStatusCode int) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(httpStatusCode) + w.Write(resp) }