|
| 1 | +package errhandler |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "net/http" |
| 6 | +) |
| 7 | + |
| 8 | +// ErrHandlerFunc wraps http.HandlerFunc, allowing for errors to be handled |
| 9 | +// in a more familiar way inside your handlers. |
| 10 | +type ErrHandlerFunc func(w http.ResponseWriter, r *http.Request) error |
| 11 | + |
| 12 | +// ServeHTTP is invoked when the HTTP handler is called, capturing and returning |
| 13 | +// any errors encountered in the ErrHandlerFunc. |
| 14 | +func (fn ErrHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 15 | + if err := fn(w, r); err != nil { |
| 16 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +// SendJSON returns a JSON response to the caller, or fails with an error. |
| 21 | +func SendJSON(w http.ResponseWriter, data interface{}) error { |
| 22 | + w.Header().Set("Content-Type", "application/json") |
| 23 | + w.WriteHeader(http.StatusOK) |
| 24 | + if err := json.NewEncoder(w).Encode(data); err != nil { |
| 25 | + return err |
| 26 | + } |
| 27 | + return nil |
| 28 | +} |
| 29 | + |
| 30 | +// SendString returns a string response to the caller, or fails with an error. |
| 31 | +func SendString(w http.ResponseWriter, message string) error { |
| 32 | + w.Header().Set("Content-Type", "text/plain") |
| 33 | + w.WriteHeader(http.StatusOK) |
| 34 | + if _, err := w.Write([]byte(message)); err != nil { |
| 35 | + return err |
| 36 | + } |
| 37 | + return nil |
| 38 | +} |
| 39 | + |
| 40 | +// ParseJSON can be used to parse a string from the body of a request. |
| 41 | +func ParseJSON(r *http.Request, val any) error { |
| 42 | + return json.NewDecoder(r.Body).Decode(val) |
| 43 | +} |
0 commit comments