homebox/backend/pkgs/server/response.go

59 lines
1.7 KiB
Go
Raw Permalink Normal View History

2022-08-30 02:30:36 +00:00
package server
import (
"encoding/json"
"errors"
"net/http"
)
// 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-08-31 00:40:27 +00:00
func Respond(w http.ResponseWriter, statusCode int, data interface{}) {
2022-08-30 02:30:36 +00:00
if statusCode == http.StatusNoContent {
w.WriteHeader(statusCode)
2022-08-31 00:40:27 +00:00
return
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 {
2022-08-31 00:40:27 +00:00
panic(err)
2022-08-30 02:30:36 +00:00
}
}
// ResponseError is a helper function that sends a JSON response of an error message
func RespondError(w http.ResponseWriter, statusCode int, err error) {
eb := ErrorBuilder{}
eb.AddError(err)
eb.Respond(w, statusCode)
}
2022-08-31 00:40:27 +00:00
// RespondServerError is a wrapper around RespondError that sends a 500 internal server error. Useful for
2022-08-30 02:30:36 +00:00
// Sending generic errors when everything went wrong.
2022-08-31 00:40:27 +00:00
func RespondServerError(w http.ResponseWriter) {
2022-08-30 02:30:36 +00:00
RespondError(w, http.StatusInternalServerError, errors.New("internal server error"))
}
// RespondNotFound is a helper utility for responding with a generic
// "unauthorized" error.
func RespondUnauthorized(w http.ResponseWriter) {
RespondError(w, http.StatusUnauthorized, errors.New("unauthorized"))
}
// RespondForbidden is a helper utility for responding with a generic
// "forbidden" error.
func RespondForbidden(w http.ResponseWriter) {
RespondError(w, http.StatusForbidden, errors.New("forbidden"))
}