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
|
// Response is a JSON encoded HTTP response body
|
||||||
type Response struct {
|
type Response struct {
|
||||||
Error *Error `json:",omitempty"`
|
Error *Error `json:"error,omitempty"`
|
||||||
Data interface{} `json:",omitempty"`
|
Data interface{} `json:"data,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ErrorCode string
|
type ErrorCode string
|
||||||
|
|
||||||
// Error is a JSON encoded error
|
// Error is a JSON encoded error
|
||||||
type Error struct {
|
type Error struct {
|
||||||
Code ErrorCode
|
Code ErrorCode `json:"code"`
|
||||||
Data interface{} `json:",omitempty"`
|
Data interface{} `json:"data,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *Error) Error() string {
|
func (e *Error) Error() string {
|
||||||
|
@ -27,20 +27,22 @@ func (e *Error) Error() string {
|
||||||
func DataResponse(w http.ResponseWriter, status int, data interface{}) {
|
func DataResponse(w http.ResponseWriter, status int, data interface{}) {
|
||||||
response(w, status, &Response{
|
response(w, status, &Response{
|
||||||
Data: data,
|
Data: data,
|
||||||
})
|
}, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
func ErrorResponse(w http.ResponseWriter, status int, code ErrorCode, data interface{}) {
|
func ErrorResponse(w http.ResponseWriter, status int, code ErrorCode, data interface{}) {
|
||||||
response(w, status, &Response{
|
response(w, status, &Response{
|
||||||
Error: &Error{code, data},
|
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.Header().Set("Content-Type", "application/json")
|
||||||
w.WriteHeader(status)
|
w.WriteHeader(status)
|
||||||
|
|
||||||
encoder := json.NewEncoder(w)
|
encoder := json.NewEncoder(w)
|
||||||
encoder.SetIndent("", " ")
|
encoder.SetIndent("", " ")
|
||||||
|
|
||||||
if err := encoder.Encode(res); err != nil {
|
if err := encoder.Encode(res); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue