2022-08-30 02:30:36 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2022-10-30 02:15:35 +00:00
|
|
|
type ErrorResponse struct {
|
|
|
|
Error string `json:"error"`
|
|
|
|
Fields map[string]string `json:"fields,omitempty"`
|
|
|
|
}
|
|
|
|
|
2022-08-30 02:30:36 +00:00
|
|
|
// Respond converts a Go value to JSON and sends it to the client.
|
|
|
|
// Adapted from https://github.com/ardanlabs/service/tree/master/foundation/web
|
2022-10-30 02:15:35 +00:00
|
|
|
func Respond(w http.ResponseWriter, statusCode int, data interface{}) error {
|
2022-08-30 02:30:36 +00:00
|
|
|
if statusCode == http.StatusNoContent {
|
|
|
|
w.WriteHeader(statusCode)
|
2022-10-30 02:15:35 +00:00
|
|
|
return nil
|
2022-08-30 02:30:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Convert the response value to JSON.
|
|
|
|
jsonData, err := json.Marshal(data)
|
|
|
|
if err != nil {
|
2022-08-31 00:40:27 +00:00
|
|
|
panic(err)
|
2022-08-30 02:30:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set the content type and headers once we know marshaling has succeeded.
|
2022-10-07 02:54:09 +00:00
|
|
|
w.Header().Set("Content-Type", ContentJSON)
|
2022-08-30 02:30:36 +00:00
|
|
|
|
|
|
|
// Write the status code to the response.
|
|
|
|
w.WriteHeader(statusCode)
|
|
|
|
|
|
|
|
// Send the result back to the client.
|
|
|
|
if _, err := w.Write(jsonData); err != nil {
|
2022-10-30 02:15:35 +00:00
|
|
|
return err
|
2022-08-30 02:30:36 +00:00
|
|
|
}
|
|
|
|
|
2022-10-30 02:15:35 +00:00
|
|
|
return nil
|
2022-08-30 02:30:36 +00:00
|
|
|
}
|