Documentation
¶
Overview ¶
Package api reads and answers HTTP requests: JSON bodies within a limit, and errors with the status a system's error carries. A system declares each error a person can be shown with Invalid, Forbidden, NotFound, Conflict, or Unavailable, whose text is the sentence the person reads. WriteError sends that sentence with the matching status, and any other error as a logged 500 with a generic message, so no internal detail reaches a browser.
Index ¶
- Constants
- Variables
- func Conflict(text string) error
- func Forbidden(text string) error
- func Invalid(text string) error
- func LimitBodies(limit int64, next http.Handler) http.Handler
- func LimitBody(limit int64, next http.Handler) http.Handler
- func NotFound(text string) error
- func ReadJSON(request *http.Request, value any) error
- func Unavailable(text string) error
- func WriteError(writer http.ResponseWriter, request *http.Request, err error)
- func WriteJSON(writer http.ResponseWriter, status int, value any)
Constants ¶
const DefaultBodyLimit = 1 << 20
DefaultBodyLimit is the request body size LimitBodies allows on a route with no limit of its own: plenty for a JSON body.
Variables ¶
var ErrNotJSON = Invalid("The request body is not valid JSON.")
ErrNotJSON is the answer when a request body cannot be decoded.
Functions ¶
func LimitBodies ¶ added in v0.8.0
LimitBodies caps every request body at limit bytes, so no handler can be made to read without bound. Wrap the mux once. A handler that reads past the limit gets an *http.MaxBytesError, which WriteError answers with 413.
func LimitBody ¶ added in v0.8.0
LimitBody gives one route its own limit, larger or smaller than LimitBodies' default, such as an upload. It may sit anywhere on the route's line before anything that reads the body: it caps the body LimitBodies received, not the one LimitBodies already capped. When two sit on one line, the one nearest the handler wins.
func ReadJSON ¶ added in v0.8.0
ReadJSON decodes the request body into value: one JSON value and nothing after it. A body over its limit returns the *http.MaxBytesError, which WriteError answers with 413; anything else that fails returns ErrNotJSON.
func Unavailable ¶ added in v0.9.0
Unavailable is an error for a service the system depends on that did not answer, so the person should try again later, answered with 503.
func WriteError ¶
func WriteError(writer http.ResponseWriter, request *http.Request, err error)
WriteError answers with {"error": text}. An error made by Invalid, Forbidden, NotFound, Conflict, or Unavailable, even when wrapped, is sent with its own text and status; an Unavailable one is also logged as a warning with everything it wraps, which says what did not answer. A body over its limit is 413. Any other error is logged with the request and answered with 500 and a generic message.
Types ¶
This section is empty.