feat(api): use conventional data and error keys json casing
This commit is contained in:
parent
cc89f755cf
commit
dec695f0e2
16
api/api.go
16
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)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue