feat(api): use conventional data and error keys json casing

This commit is contained in:
wpetit 2023-02-06 09:30:46 +01:00
parent cc89f755cf
commit dec695f0e2
1 changed files with 9 additions and 7 deletions

View File

@ -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)
}