| 1 | // Package httpx has the small JSON helpers every handler uses. |
| 2 | package httpx |
| 3 | |
| 4 | import ( |
| 5 | "encoding/json" |
| 6 | "log/slog" |
| 7 | "net/http" |
| 8 | ) |
| 9 | |
| 10 | // JSON writes v as the response, with the given status. |
| 11 | func JSON(w http.ResponseWriter, status int, v any) { |
| 12 | w.Header().Set("Content-Type", "application/json") |
| 13 | w.WriteHeader(status) |
| 14 | json.NewEncoder(w).Encode(v) |
| 15 | } |
| 16 | |
| 17 | // Error writes {"error": msg} with the given status. |
| 18 | func Error(w http.ResponseWriter, status int, msg string) { |
| 19 | JSON(w, status, map[string]string{"error": msg}) |
| 20 | } |
| 21 | |
| 22 | // ServerError logs err and answers 500, without telling the client what broke. |
| 23 | func ServerError(w http.ResponseWriter, r *http.Request, err error) { |
| 24 | slog.ErrorContext(r.Context(), "request failed", "method", r.Method, "path", r.URL.Path, "error", err) |
| 25 | Error(w, http.StatusInternalServerError, "internal error") |
| 26 | } |
| 27 | |
| 28 | // Decode reads a JSON body of at most 1 MB into v. |
| 29 | func Decode(w http.ResponseWriter, r *http.Request, v any) error { |
| 30 | return json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(v) |
| 31 | } |