json.go91 lines, 3.0 KB
| 1 | package httpx |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | // maxBodyBytes caps request bodies. Our requests are tiny, and the cap stops a |
| 13 | // client from making us read a huge body into memory. |
| 14 | const maxBodyBytes = 1 << 20 // 1 MiB |
| 15 | |
| 16 | // WriteJSON sends v as JSON with the given status. It encodes v before writing |
| 17 | // anything, so an encoding bug becomes a clean 500 instead of half a response. |
| 18 | func WriteJSON(w http.ResponseWriter, r *http.Request, status int, v any) { |
| 19 | body, err := json.Marshal(v) |
| 20 | if err != nil { |
| 21 | Error(w, r, fmt.Errorf("encode response: %w", err)) |
| 22 | return |
| 23 | } |
| 24 | writeBody(w, status, body) |
| 25 | } |
| 26 | |
| 27 | func writeBody(w http.ResponseWriter, status int, body []byte) { |
| 28 | w.Header().Set("Content-Type", "application/json") |
| 29 | w.WriteHeader(status) |
| 30 | w.Write(append(body, '\n')) |
| 31 | } |
| 32 | |
| 33 | // DecodeJSON reads the request body into dst. It is strict on purpose: one |
| 34 | // JSON value, at most 1 MiB, and no fields that dst doesn't have. Problems |
| 35 | // come back as errors that Error turns into a 400 or a 413. |
| 36 | func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any) error { |
| 37 | dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes)) |
| 38 | dec.DisallowUnknownFields() |
| 39 | if err := dec.Decode(dst); err != nil { |
| 40 | return decodeError(err) |
| 41 | } |
| 42 | if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) { |
| 43 | return badRequest("body must contain a single JSON value") |
| 44 | } |
| 45 | return nil |
| 46 | } |
| 47 | |
| 48 | // requestError is a problem with the request itself, such as a body that |
| 49 | // isn't valid JSON, rather than with what it asks us to do. |
| 50 | type requestError struct { |
| 51 | status int |
| 52 | code string |
| 53 | msg string |
| 54 | } |
| 55 | |
| 56 | func (e *requestError) Error() string { return e.msg } |
| 57 | |
| 58 | func badRequest(msg string) error { |
| 59 | return &requestError{http.StatusBadRequest, "bad_request", msg} |
| 60 | } |
| 61 | |
| 62 | // NewError returns an error that Error sends with exactly this status and |
| 63 | // code. It's for problems with the request itself, like a missing header. |
| 64 | func NewError(status int, code, msg string) error { |
| 65 | return &requestError{status, code, msg} |
| 66 | } |
| 67 | |
| 68 | // decodeError turns encoding/json's errors into messages a client can act on. |
| 69 | func decodeError(err error) error { |
| 70 | var syntaxErr *json.SyntaxError |
| 71 | var typeErr *json.UnmarshalTypeError |
| 72 | var sizeErr *http.MaxBytesError |
| 73 | switch { |
| 74 | case errors.Is(err, io.EOF): |
| 75 | return badRequest("body must not be empty") |
| 76 | case errors.As(err, &syntaxErr): |
| 77 | return badRequest(fmt.Sprintf("malformed JSON at byte %d", syntaxErr.Offset)) |
| 78 | case errors.Is(err, io.ErrUnexpectedEOF): |
| 79 | return badRequest("malformed JSON") |
| 80 | case errors.As(err, &typeErr): |
| 81 | return badRequest(fmt.Sprintf("field %q must be of type %s", typeErr.Field, typeErr.Type)) |
| 82 | case strings.HasPrefix(err.Error(), "json: unknown field "): |
| 83 | // encoding/json has no error type for this case, only the message. |
| 84 | return badRequest(strings.TrimPrefix(err.Error(), "json: ")) |
| 85 | case errors.As(err, &sizeErr): |
| 86 | msg := fmt.Sprintf("body must be at most %d bytes", sizeErr.Limit) |
| 87 | return &requestError{http.StatusRequestEntityTooLarge, "body_too_large", msg} |
| 88 | default: |
| 89 | return badRequest("invalid JSON body") |
| 90 | } |
| 91 | } |