Documentation
¶
Overview ¶
Package httpcompress encodes compressible HTTP responses (JSON, XML, YAML, plain text) with zstd or gzip, as the client's Accept-Encoding allows.
It is for metadata and API documents, never for artifact bytes: the middleware is mounted on routes that serve documents, and it additionally leaves alone every response that is a download (Content-Disposition), is already encoded or ranged, is not of a text type, or is smaller than MinSize.
The wrapped writer is transparent: it keeps io.ReaderFrom (so a response it leaves alone is still sent with sendfile(2)), http.Flusher and, through Unwrap, everything http.ResponseController reaches (Hijack, deadlines).
Index ¶
Constants ¶
const MinSize = 1024
MinSize is the smallest body worth compressing: below it the framing and the CPU cost outweigh the savings, and a small response is faster sent as is.
Variables ¶
This section is empty.
Functions ¶
func Func ¶
func Func(next http.HandlerFunc) http.HandlerFunc
Func is Middleware for a handler function that serves documents on GET only; every other method goes straight to next.
func Middleware ¶
Middleware compresses the compressible responses of next for clients that accept an encoding.
Semantics, per RFC 9110 and 9111:
- Only 200 responses of a text type (text/*, +json, +xml, +yaml, application/json, ...) that carry no Content-Encoding, Content-Range, Content-Disposition or "Cache-Control: no-transform" are encoded.
- Requests with Range or Upgrade, and HEAD requests, pass through untouched: a range addresses the identity representation, and a HEAD answer cannot know the encoded length.
- A body below MinSize (by Content-Length, or once the handler is done) is sent as is. Responses the handler flushes are streamed encoded.
- An encoded response drops Content-Length and Accept-Ranges, gets "Vary: Accept-Encoding" and, when it has an entity tag, a weak one: the encoded and the plain bytes differ, so the strong tag no longer names them. If-None-Match uses weak comparison, so a client revalidating with the weak tag still gets its 304 from the handler.
- "Vary: Accept-Encoding" is added to every response whose representation depends on the header, including the plain ones, so no cache can hand an encoded body to a client that did not ask for it or the reverse.
Types ¶
This section is empty.