mirror of
https://github.com/hay-kot/homebox.git
synced 2025-07-26 20:40:26 +00:00
refactor: http interfaces (#114)
* implement custom http handler interface * implement trace_id * normalize http method spacing for consistent logs * fix failing test * fix linter errors * cleanup old dead code * more route cleanup * cleanup some inconsistent errors * update and generate code * make taskfile more consistent * update task calls * run tidy * drop `@` tag for version * use relative paths * tidy * fix auto-setting variables * update build paths * add contributing guide * tidy
This commit is contained in:
parent
e2d93f8523
commit
6529549289
40 changed files with 984 additions and 808 deletions
|
@ -2,16 +2,20 @@ package server
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
Fields map[string]string `json:"fields,omitempty"`
|
||||
}
|
||||
|
||||
// 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{}) {
|
||||
func Respond(w http.ResponseWriter, statusCode int, data interface{}) error {
|
||||
if statusCode == http.StatusNoContent {
|
||||
w.WriteHeader(statusCode)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert the response value to JSON.
|
||||
|
@ -28,31 +32,8 @@ func Respond(w http.ResponseWriter, statusCode int, data interface{}) {
|
|||
|
||||
// Send the result back to the client.
|
||||
if _, err := w.Write(jsonData); err != nil {
|
||||
panic(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// RespondServerError is a wrapper around RespondError that sends a 500 internal server error. Useful for
|
||||
// Sending generic errors when everything went wrong.
|
||||
func RespondServerError(w http.ResponseWriter) {
|
||||
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"))
|
||||
return nil
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue