From dec695f0e2e927f726a7f99fd462f2dfc0609871 Mon Sep 17 00:00:00 2001 From: William Petit Date: Mon, 6 Feb 2023 09:30:46 +0100 Subject: [PATCH] feat(api): use conventional data and error keys json casing --- api/api.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/api/api.go b/api/api.go index 7f8f5cd..7bea4d3 100644 --- a/api/api.go +++ b/api/api.go @@ -8,16 +8,16 @@ import ( // Response is a JSON encoded HTTP response body type Response struct { - Error *Error `json:",omitempty"` - Data interface{} `json:",omitempty"` + Error *Error `json:"error,omitempty"` + Data interface{} `json:"data,omitempty"` } type ErrorCode string // Error is a JSON encoded error type Error struct { - Code ErrorCode - Data interface{} `json:",omitempty"` + Code ErrorCode `json:"code"` + Data interface{} `json:"data,omitempty"` } func (e *Error) Error() string { @@ -27,20 +27,22 @@ func (e *Error) Error() string { func DataResponse(w http.ResponseWriter, status int, data interface{}) { response(w, status, &Response{ Data: data, - }) + }, false) } func ErrorResponse(w http.ResponseWriter, status int, code ErrorCode, data interface{}) { response(w, status, &Response{ Error: &Error{code, data}, - }) + }, false) } -func response(w http.ResponseWriter, status int, res *Response) { +func response(w http.ResponseWriter, status int, res *Response, conventional bool) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) + encoder := json.NewEncoder(w) encoder.SetIndent("", " ") + if err := encoder.Encode(res); err != nil { panic(err) }