compress.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. package middleware
  2. import (
  3. "bufio"
  4. "compress/flate"
  5. "compress/gzip"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net"
  10. "net/http"
  11. "strings"
  12. "sync"
  13. )
  14. var defaultCompressibleContentTypes = []string{
  15. "text/html",
  16. "text/css",
  17. "text/plain",
  18. "text/javascript",
  19. "application/javascript",
  20. "application/x-javascript",
  21. "application/json",
  22. "application/atom+xml",
  23. "application/rss+xml",
  24. "image/svg+xml",
  25. }
  26. // Compress is a middleware that compresses response
  27. // body of a given content types to a data format based
  28. // on Accept-Encoding request header. It uses a given
  29. // compression level.
  30. //
  31. // NOTE: make sure to set the Content-Type header on your response
  32. // otherwise this middleware will not compress the response body. For ex, in
  33. // your handler you should set w.Header().Set("Content-Type", http.DetectContentType(yourBody))
  34. // or set it manually.
  35. //
  36. // Passing a compression level of 5 is sensible value
  37. func Compress(level int, types ...string) func(next http.Handler) http.Handler {
  38. compressor := NewCompressor(level, types...)
  39. return compressor.Handler
  40. }
  41. // Compressor represents a set of encoding configurations.
  42. type Compressor struct {
  43. // The mapping of encoder names to encoder functions.
  44. encoders map[string]EncoderFunc
  45. // The mapping of pooled encoders to pools.
  46. pooledEncoders map[string]*sync.Pool
  47. // The set of content types allowed to be compressed.
  48. allowedTypes map[string]struct{}
  49. allowedWildcards map[string]struct{}
  50. // The list of encoders in order of decreasing precedence.
  51. encodingPrecedence []string
  52. level int // The compression level.
  53. }
  54. // NewCompressor creates a new Compressor that will handle encoding responses.
  55. //
  56. // The level should be one of the ones defined in the flate package.
  57. // The types are the content types that are allowed to be compressed.
  58. func NewCompressor(level int, types ...string) *Compressor {
  59. // If types are provided, set those as the allowed types. If none are
  60. // provided, use the default list.
  61. allowedTypes := make(map[string]struct{})
  62. allowedWildcards := make(map[string]struct{})
  63. if len(types) > 0 {
  64. for _, t := range types {
  65. if strings.Contains(strings.TrimSuffix(t, "/*"), "*") {
  66. panic(fmt.Sprintf("middleware/compress: Unsupported content-type wildcard pattern '%s'. Only '/*' supported", t))
  67. }
  68. if strings.HasSuffix(t, "/*") {
  69. allowedWildcards[strings.TrimSuffix(t, "/*")] = struct{}{}
  70. } else {
  71. allowedTypes[t] = struct{}{}
  72. }
  73. }
  74. } else {
  75. for _, t := range defaultCompressibleContentTypes {
  76. allowedTypes[t] = struct{}{}
  77. }
  78. }
  79. c := &Compressor{
  80. level: level,
  81. encoders: make(map[string]EncoderFunc),
  82. pooledEncoders: make(map[string]*sync.Pool),
  83. allowedTypes: allowedTypes,
  84. allowedWildcards: allowedWildcards,
  85. }
  86. // Set the default encoders. The precedence order uses the reverse
  87. // ordering that the encoders were added. This means adding new encoders
  88. // will move them to the front of the order.
  89. //
  90. // TODO:
  91. // lzma: Opera.
  92. // sdch: Chrome, Android. Gzip output + dictionary header.
  93. // br: Brotli, see https://github.com/go-chi/chi/pull/326
  94. // HTTP 1.1 "deflate" (RFC 2616) stands for DEFLATE data (RFC 1951)
  95. // wrapped with zlib (RFC 1950). The zlib wrapper uses Adler-32
  96. // checksum compared to CRC-32 used in "gzip" and thus is faster.
  97. //
  98. // But.. some old browsers (MSIE, Safari 5.1) incorrectly expect
  99. // raw DEFLATE data only, without the mentioned zlib wrapper.
  100. // Because of this major confusion, most modern browsers try it
  101. // both ways, first looking for zlib headers.
  102. // Quote by Mark Adler: http://stackoverflow.com/a/9186091/385548
  103. //
  104. // The list of browsers having problems is quite big, see:
  105. // http://zoompf.com/blog/2012/02/lose-the-wait-http-compression
  106. // https://web.archive.org/web/20120321182910/http://www.vervestudios.co/projects/compression-tests/results
  107. //
  108. // That's why we prefer gzip over deflate. It's just more reliable
  109. // and not significantly slower than deflate.
  110. c.SetEncoder("deflate", encoderDeflate)
  111. // TODO: Exception for old MSIE browsers that can't handle non-HTML?
  112. // https://zoompf.com/blog/2012/02/lose-the-wait-http-compression
  113. c.SetEncoder("gzip", encoderGzip)
  114. // NOTE: Not implemented, intentionally:
  115. // case "compress": // LZW. Deprecated.
  116. // case "bzip2": // Too slow on-the-fly.
  117. // case "zopfli": // Too slow on-the-fly.
  118. // case "xz": // Too slow on-the-fly.
  119. return c
  120. }
  121. // SetEncoder can be used to set the implementation of a compression algorithm.
  122. //
  123. // The encoding should be a standardised identifier. See:
  124. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
  125. //
  126. // For example, add the Brotli algorithm:
  127. //
  128. // import brotli_enc "gopkg.in/kothar/brotli-go.v0/enc"
  129. //
  130. // compressor := middleware.NewCompressor(5, "text/html")
  131. // compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer {
  132. // params := brotli_enc.NewBrotliParams()
  133. // params.SetQuality(level)
  134. // return brotli_enc.NewBrotliWriter(params, w)
  135. // })
  136. func (c *Compressor) SetEncoder(encoding string, fn EncoderFunc) {
  137. encoding = strings.ToLower(encoding)
  138. if encoding == "" {
  139. panic("the encoding can not be empty")
  140. }
  141. if fn == nil {
  142. panic("attempted to set a nil encoder function")
  143. }
  144. // If we are adding a new encoder that is already registered, we have to
  145. // clear that one out first.
  146. delete(c.pooledEncoders, encoding)
  147. delete(c.encoders, encoding)
  148. // If the encoder supports Resetting (IoReseterWriter), then it can be pooled.
  149. encoder := fn(io.Discard, c.level)
  150. if _, ok := encoder.(ioResetterWriter); ok {
  151. pool := &sync.Pool{
  152. New: func() interface{} {
  153. return fn(io.Discard, c.level)
  154. },
  155. }
  156. c.pooledEncoders[encoding] = pool
  157. }
  158. // If the encoder is not in the pooledEncoders, add it to the normal encoders.
  159. if _, ok := c.pooledEncoders[encoding]; !ok {
  160. c.encoders[encoding] = fn
  161. }
  162. for i, v := range c.encodingPrecedence {
  163. if v == encoding {
  164. c.encodingPrecedence = append(c.encodingPrecedence[:i], c.encodingPrecedence[i+1:]...)
  165. }
  166. }
  167. c.encodingPrecedence = append([]string{encoding}, c.encodingPrecedence...)
  168. }
  169. // Handler returns a new middleware that will compress the response based on the
  170. // current Compressor.
  171. func (c *Compressor) Handler(next http.Handler) http.Handler {
  172. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  173. encoder, encoding, cleanup := c.selectEncoder(r.Header, w)
  174. cw := &compressResponseWriter{
  175. ResponseWriter: w,
  176. w: w,
  177. contentTypes: c.allowedTypes,
  178. contentWildcards: c.allowedWildcards,
  179. encoding: encoding,
  180. compressible: false, // determined in post-handler
  181. }
  182. if encoder != nil {
  183. cw.w = encoder
  184. }
  185. // Re-add the encoder to the pool if applicable.
  186. defer cleanup()
  187. defer cw.Close()
  188. next.ServeHTTP(cw, r)
  189. })
  190. }
  191. // selectEncoder returns the encoder, the name of the encoder, and a closer function.
  192. func (c *Compressor) selectEncoder(h http.Header, w io.Writer) (io.Writer, string, func()) {
  193. header := h.Get("Accept-Encoding")
  194. // Parse the names of all accepted algorithms from the header.
  195. accepted := strings.Split(strings.ToLower(header), ",")
  196. // Find supported encoder by accepted list by precedence
  197. for _, name := range c.encodingPrecedence {
  198. if matchAcceptEncoding(accepted, name) {
  199. if pool, ok := c.pooledEncoders[name]; ok {
  200. encoder := pool.Get().(ioResetterWriter)
  201. cleanup := func() {
  202. pool.Put(encoder)
  203. }
  204. encoder.Reset(w)
  205. return encoder, name, cleanup
  206. }
  207. if fn, ok := c.encoders[name]; ok {
  208. return fn(w, c.level), name, func() {}
  209. }
  210. }
  211. }
  212. // No encoder found to match the accepted encoding
  213. return nil, "", func() {}
  214. }
  215. func matchAcceptEncoding(accepted []string, encoding string) bool {
  216. for _, v := range accepted {
  217. if strings.Contains(v, encoding) {
  218. return true
  219. }
  220. }
  221. return false
  222. }
  223. // An EncoderFunc is a function that wraps the provided io.Writer with a
  224. // streaming compression algorithm and returns it.
  225. //
  226. // In case of failure, the function should return nil.
  227. type EncoderFunc func(w io.Writer, level int) io.Writer
  228. // Interface for types that allow resetting io.Writers.
  229. type ioResetterWriter interface {
  230. io.Writer
  231. Reset(w io.Writer)
  232. }
  233. type compressResponseWriter struct {
  234. http.ResponseWriter
  235. // The streaming encoder writer to be used if there is one. Otherwise,
  236. // this is just the normal writer.
  237. w io.Writer
  238. contentTypes map[string]struct{}
  239. contentWildcards map[string]struct{}
  240. encoding string
  241. wroteHeader bool
  242. compressible bool
  243. }
  244. func (cw *compressResponseWriter) isCompressible() bool {
  245. // Parse the first part of the Content-Type response header.
  246. contentType := cw.Header().Get("Content-Type")
  247. contentType, _, _ = strings.Cut(contentType, ";")
  248. // Is the content type compressible?
  249. if _, ok := cw.contentTypes[contentType]; ok {
  250. return true
  251. }
  252. if contentType, _, hadSlash := strings.Cut(contentType, "/"); hadSlash {
  253. _, ok := cw.contentWildcards[contentType]
  254. return ok
  255. }
  256. return false
  257. }
  258. func (cw *compressResponseWriter) WriteHeader(code int) {
  259. if cw.wroteHeader {
  260. cw.ResponseWriter.WriteHeader(code) // Allow multiple calls to propagate.
  261. return
  262. }
  263. cw.wroteHeader = true
  264. defer cw.ResponseWriter.WriteHeader(code)
  265. // Already compressed data?
  266. if cw.Header().Get("Content-Encoding") != "" {
  267. return
  268. }
  269. if !cw.isCompressible() {
  270. cw.compressible = false
  271. return
  272. }
  273. if cw.encoding != "" {
  274. cw.compressible = true
  275. cw.Header().Set("Content-Encoding", cw.encoding)
  276. cw.Header().Add("Vary", "Accept-Encoding")
  277. // The content-length after compression is unknown
  278. cw.Header().Del("Content-Length")
  279. }
  280. }
  281. func (cw *compressResponseWriter) Write(p []byte) (int, error) {
  282. if !cw.wroteHeader {
  283. cw.WriteHeader(http.StatusOK)
  284. }
  285. return cw.writer().Write(p)
  286. }
  287. func (cw *compressResponseWriter) writer() io.Writer {
  288. if cw.compressible {
  289. return cw.w
  290. }
  291. return cw.ResponseWriter
  292. }
  293. type compressFlusher interface {
  294. Flush() error
  295. }
  296. func (cw *compressResponseWriter) Flush() {
  297. if f, ok := cw.writer().(http.Flusher); ok {
  298. f.Flush()
  299. }
  300. // If the underlying writer has a compression flush signature,
  301. // call this Flush() method instead
  302. if f, ok := cw.writer().(compressFlusher); ok {
  303. f.Flush()
  304. // Also flush the underlying response writer
  305. if f, ok := cw.ResponseWriter.(http.Flusher); ok {
  306. f.Flush()
  307. }
  308. }
  309. }
  310. func (cw *compressResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  311. if hj, ok := cw.writer().(http.Hijacker); ok {
  312. return hj.Hijack()
  313. }
  314. return nil, nil, errors.New("chi/middleware: http.Hijacker is unavailable on the writer")
  315. }
  316. func (cw *compressResponseWriter) Push(target string, opts *http.PushOptions) error {
  317. if ps, ok := cw.writer().(http.Pusher); ok {
  318. return ps.Push(target, opts)
  319. }
  320. return errors.New("chi/middleware: http.Pusher is unavailable on the writer")
  321. }
  322. func (cw *compressResponseWriter) Close() error {
  323. if c, ok := cw.writer().(io.WriteCloser); ok {
  324. return c.Close()
  325. }
  326. return errors.New("chi/middleware: io.WriteCloser is unavailable on the writer")
  327. }
  328. func (cw *compressResponseWriter) Unwrap() http.ResponseWriter {
  329. return cw.ResponseWriter
  330. }
  331. func encoderGzip(w io.Writer, level int) io.Writer {
  332. gw, err := gzip.NewWriterLevel(w, level)
  333. if err != nil {
  334. return nil
  335. }
  336. return gw
  337. }
  338. func encoderDeflate(w io.Writer, level int) io.Writer {
  339. dw, err := flate.NewWriter(w, level)
  340. if err != nil {
  341. return nil
  342. }
  343. return dw
  344. }