Add ability to control the format of the json response from api server.
This commit is contained in:
parent
a391c83a2f
commit
9b6fea461c
1 changed files with 17 additions and 11 deletions
|
@ -20,6 +20,19 @@ var ResponseHeaders map[string]string
|
||||||
// Log allows logging of events and errors
|
// Log allows logging of events and errors
|
||||||
var Log = func(*http.Request, *Response, error) {}
|
var Log = func(*http.Request, *Response, error) {}
|
||||||
|
|
||||||
|
// http://choly.ca/post/go-json-marshalling/
|
||||||
|
type ResponseInfo struct {
|
||||||
|
Success bool `json:"success"`
|
||||||
|
Error *string `json:"error"`
|
||||||
|
Data interface{} `json:"data"`
|
||||||
|
Trace []string `json:"_trace,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildJSONResponse allows implementers to control the json response form from the api
|
||||||
|
var BuildJSONResponse = func(response ResponseInfo) ([]byte, error) {
|
||||||
|
return json.MarshalIndent(&response, "", " ")
|
||||||
|
}
|
||||||
|
|
||||||
// TraceEnabled Attaches a trace field to the JSON response when enabled.
|
// TraceEnabled Attaches a trace field to the JSON response when enabled.
|
||||||
var TraceEnabled = false
|
var TraceEnabled = false
|
||||||
|
|
||||||
|
@ -116,27 +129,20 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
trace = getTraceFromError(rsp.Error)
|
trace = getTraceFromError(rsp.Error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// http://choly.ca/post/go-json-marshalling/
|
jsonResponse, err := BuildJSONResponse(ResponseInfo{
|
||||||
type apiResponse struct {
|
|
||||||
Success bool `json:"success"`
|
|
||||||
Error *string `json:"error"`
|
|
||||||
Data interface{} `json:"data"`
|
|
||||||
Trace []string `json:"_trace,omitempty"`
|
|
||||||
}
|
|
||||||
jsonResponse, err := json.MarshalIndent(&apiResponse{
|
|
||||||
Success: success,
|
Success: success,
|
||||||
Error: errorString,
|
Error: errorString,
|
||||||
Data: rsp.Data,
|
Data: rsp.Data,
|
||||||
Trace: trace,
|
Trace: trace,
|
||||||
}, "", " ")
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Log(r, &rsp, errors.Prefix("Error encoding JSON response: ", err))
|
Log(r, &rsp, errors.Prefix("Error encoding JSON response: ", err))
|
||||||
jsonResponse, err = json.MarshalIndent(&apiResponse{
|
jsonResponse, err = BuildJSONResponse(ResponseInfo{
|
||||||
Success: false,
|
Success: false,
|
||||||
Error: util.PtrToString(err.Error()),
|
Error: util.PtrToString(err.Error()),
|
||||||
Data: nil,
|
Data: nil,
|
||||||
Trace: getTraceFromError(err),
|
Trace: getTraceFromError(err),
|
||||||
}, "", " ")
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Log(r, &rsp, errors.Prefix("Error encoding JSON response: ", err))
|
Log(r, &rsp, errors.Prefix("Error encoding JSON response: ", err))
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue