2021-06-20 19:52:43 +00:00
|
|
|
package aicra
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/xdrm-io/aicra/api"
|
|
|
|
)
|
|
|
|
|
|
|
|
// response for an service call
|
|
|
|
type response struct {
|
2021-06-20 19:52:43 +00:00
|
|
|
Data map[string]interface{}
|
|
|
|
Status int
|
|
|
|
err api.Err
|
2021-06-20 19:52:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// newResponse creates an empty response.
|
|
|
|
func newResponse() *response {
|
|
|
|
return &response{
|
2021-06-20 19:52:43 +00:00
|
|
|
Status: http.StatusOK,
|
|
|
|
Data: make(map[string]interface{}),
|
|
|
|
err: api.ErrFailure,
|
2021-06-20 19:52:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithError sets the response error
|
2021-06-20 19:52:43 +00:00
|
|
|
func (r *response) WithError(err api.Err) *response {
|
|
|
|
r.err = err
|
|
|
|
return r
|
2021-06-20 19:52:43 +00:00
|
|
|
}
|
|
|
|
|
2021-06-20 19:52:43 +00:00
|
|
|
// WithValue sets a response value
|
|
|
|
func (r *response) WithValue(name string, value interface{}) *response {
|
|
|
|
r.Data[name] = value
|
|
|
|
return r
|
2021-06-20 19:52:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// MarshalJSON generates the JSON representation of the response
|
|
|
|
//
|
|
|
|
// implements json.Marshaler
|
2021-06-20 19:52:43 +00:00
|
|
|
func (r *response) MarshalJSON() ([]byte, error) {
|
2021-06-20 19:52:43 +00:00
|
|
|
fmt := make(map[string]interface{})
|
2021-06-20 19:52:43 +00:00
|
|
|
for k, v := range r.Data {
|
2021-06-20 19:52:43 +00:00
|
|
|
fmt[k] = v
|
|
|
|
}
|
2021-06-20 19:52:43 +00:00
|
|
|
fmt["error"] = r.err
|
2021-06-20 19:52:43 +00:00
|
|
|
return json.Marshal(fmt)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ServeHTTP writes the response representation back to the http.ResponseWriter
|
|
|
|
//
|
|
|
|
// implements http.Handler
|
|
|
|
func (res *response) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
w.WriteHeader(res.err.Status)
|
|
|
|
encoded, err := json.Marshal(res)
|
2021-06-20 19:52:43 +00:00
|
|
|
if err == nil {
|
|
|
|
w.Write(encoded)
|
2021-06-20 19:52:43 +00:00
|
|
|
}
|
2021-06-20 19:52:43 +00:00
|
|
|
return err
|
2021-06-20 19:52:43 +00:00
|
|
|
}
|