From 04390a0e546c0de0fa28d323212914d3fa384c69 Mon Sep 17 00:00:00 2001 From: Nicholas Wiersma Date: Wed, 4 Oct 2023 06:27:24 +0200 Subject: [PATCH] fix: make apierror consistent (#94) --- http/render/json.go | 11 +++++++---- http/render/json_test.go | 6 +++--- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/http/render/json.go b/http/render/json.go index 70dbfb7..a238205 100644 --- a/http/render/json.go +++ b/http/render/json.go @@ -14,8 +14,11 @@ const JSONContentType = "application/json" // APIError contains error information that is rendered by JSONError. type APIError struct { - Code int `json:"code"` - Reason string `json:"reason"` + // Code is the http status code. + Code int `json:"code"` + + // Error is the reason for the error. + Error string `json:"error"` } // JSONInternalServerError writes a JSON internal server error. @@ -33,10 +36,10 @@ func JSONError(rw http.ResponseWriter, code int, reason string) { rw.Header().Set("Content-Type", JSONContentType) rw.WriteHeader(code) - apiErr := APIError{Code: code, Reason: reason} + apiErr := APIError{Code: code, Error: reason} b, err := jsoniter.Marshal(apiErr) if err != nil { - _, _ = rw.Write([]byte(`{"reason":"Internal Server Error"}`)) + _, _ = rw.Write([]byte(`{"code":500,"error":"internal server error"}`)) } _, _ = rw.Write(b) diff --git a/http/render/json_test.go b/http/render/json_test.go index e63a81a..b61c9eb 100644 --- a/http/render/json_test.go +++ b/http/render/json_test.go @@ -15,7 +15,7 @@ func TestJSONInternalServerError(t *testing.T) { render.JSONInternalServerError(rec) - want := `{"code":500,"reason":"internal server error"}` + want := `{"code":500,"error":"internal server error"}` assert.Equal(t, http.StatusInternalServerError, rec.Code) assert.Equal(t, "application/json", rec.Header().Get("Content-Type")) assert.Equal(t, want, rec.Body.String()) @@ -26,7 +26,7 @@ func TestJSONErrorf(t *testing.T) { render.JSONErrorf(rec, http.StatusBadRequest, "test %s", "message") - want := `{"code":400,"reason":"test message"}` + want := `{"code":400,"error":"test message"}` assert.Equal(t, http.StatusBadRequest, rec.Code) assert.Equal(t, "application/json", rec.Header().Get("Content-Type")) assert.Equal(t, want, rec.Body.String()) @@ -37,7 +37,7 @@ func TestJSONError(t *testing.T) { render.JSONError(rec, http.StatusBadRequest, "test message") - want := `{"code":400,"reason":"test message"}` + want := `{"code":400,"error":"test message"}` assert.Equal(t, http.StatusBadRequest, rec.Code) assert.Equal(t, "application/json", rec.Header().Get("Content-Type")) assert.Equal(t, want, rec.Body.String())