2018-10-07 09:23:00 +00:00
|
|
|
package api
|
2018-06-01 08:51:51 +00:00
|
|
|
|
|
|
|
import (
|
2019-05-01 11:44:45 +00:00
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
2018-06-01 08:51:51 +00:00
|
|
|
)
|
|
|
|
|
2019-05-01 11:44:45 +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
|
|
|
|
Headers http.Header
|
|
|
|
Err Error
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewResponse creates an empty response
|
2018-10-07 09:23:00 +00:00
|
|
|
func NewResponse() *Response {
|
2018-06-01 08:51:51 +00:00
|
|
|
return &Response{
|
2019-05-01 11:44:45 +00:00
|
|
|
Data: make(ResponseData),
|
|
|
|
Err: ErrorFailure(),
|
2018-06-01 08:51:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-01 11:44:45 +00:00
|
|
|
// SetData adds/overrides a new response field
|
|
|
|
func (i *Response) SetData(name string, value interface{}) {
|
|
|
|
i.Data[name] = value
|
2018-06-01 08:51:51 +00:00
|
|
|
}
|
|
|
|
|
2019-05-01 11:44:45 +00:00
|
|
|
// GetData gets a response field
|
|
|
|
func (i *Response) GetData(name string) interface{} {
|
|
|
|
value, _ := i.Data[name]
|
2018-06-01 08:51:51 +00:00
|
|
|
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
2019-05-01 11:44:45 +00:00
|
|
|
// MarshalJSON implements the 'json.Marshaler' interface and is used
|
|
|
|
// to generate the JSON representation of the response
|
|
|
|
func (i *Response) MarshalJSON() ([]byte, error) {
|
2019-05-01 13:14:49 +00:00
|
|
|
fmt := make(map[string]interface{})
|
|
|
|
|
|
|
|
for k, v := range i.Data {
|
|
|
|
fmt[k] = v
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt["error"] = i.Err
|
|
|
|
|
|
|
|
return json.Marshal(fmt)
|
2018-06-01 08:51:51 +00:00
|
|
|
}
|