aicra/api/response.go

83 lines
1.7 KiB
Go
Raw Normal View History

2018-10-07 09:23:00 +00:00
package api
2018-06-01 08:51:51 +00:00
import (
"encoding/json"
"net/http"
2018-06-01 08:51:51 +00:00
)
// ResponseData defines format for response parameters to return
type ResponseData map[string]interface{}
// Response represents an API response to be sent
type Response struct {
Data ResponseData
2019-05-01 14:40:26 +00:00
Status int
Headers http.Header
Err Error
}
// NewResponse creates an empty response. An optional error can be passed as its first argument.
func NewResponse(errors ...Error) *Response {
res := &Response{
2019-05-01 14:40:26 +00:00
Status: http.StatusOK,
Data: make(ResponseData),
Err: ErrorFailure(),
Headers: make(http.Header),
2018-06-01 08:51:51 +00:00
}
// optional error
if len(errors) == 1 {
res.Err = errors[0]
}
return res
2018-06-01 08:51:51 +00:00
}
// WrapError sets the error from a base error with error arguments.
func (res *Response) WrapError(baseError Error, arguments ...interface{}) {
if len(arguments) > 0 {
baseError.SetArguments(arguments[0], arguments[1:])
}
res.Err = baseError
}
// SetData adds/overrides a new response field
func (res *Response) SetData(name string, value interface{}) {
res.Data[name] = value
2018-06-01 08:51:51 +00:00
}
// GetData gets a response field
func (res *Response) GetData(name string) interface{} {
value, _ := res.Data[name]
2018-06-01 08:51:51 +00:00
return value
}
// MarshalJSON implements the 'json.Marshaler' interface and is used
// to generate the JSON representation of the response
func (res *Response) MarshalJSON() ([]byte, error) {
2019-05-01 13:14:49 +00:00
fmt := make(map[string]interface{})
for k, v := range res.Data {
2019-05-01 13:14:49 +00:00
fmt[k] = v
}
fmt["error"] = res.Err
2019-05-01 13:14:49 +00:00
return json.Marshal(fmt)
2018-06-01 08:51:51 +00:00
}
// Write writes to an HTTP response.
func (res *Response) Write(w http.ResponseWriter) error {
w.WriteHeader(res.Status)
w.Header().Add("Content-Type", "application/json")
fmt, err := json.Marshal(res)
if err != nil {
return err
}
w.Write(fmt)
return nil
}