homebox/backend/pkgs/server/response.go

40 lines
913 B
Go
Raw Permalink Normal View History

2022-08-30 02:30:36 +00:00
package server
import (
"encoding/json"
"net/http"
)
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
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)
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.
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 {
return err
2022-08-30 02:30:36 +00:00
}
return nil
2022-08-30 02:30:36 +00:00
}