Debian Codegraph @

gzhttp/transport.go

raw
1 // Copyright (c) 2021 Klaus Post. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package gzhttp
6
7 import (
8 "io"
9 "net/http"
10 "strings"
11 "sync"
12
13 "github.com/klauspost/compress/gzip"
14 "github.com/klauspost/compress/zstd"
15 )
16
17 // Transport will wrap an HTTP transport with a custom handler
18 // that will request gzip and automatically decompress it.
19 // Using this is significantly faster than using the default transport.
20 func Transport(parent http.RoundTripper, opts ...transportOption) http.RoundTripper {
21 g := gzRoundtripper{parent: parent, withZstd: true, withGzip: true}
22 for _, o := range opts {
23 o(&g)
24 }
25 var ae []string
26 if g.withZstd {
27 ae = append(ae, "zstd")
28 }
29 if g.withGzip {
30 ae = append(ae, "gzip")
31 }
32 g.acceptEncoding = strings.Join(ae, ",")
33 return &g
34 }
35
36 type transportOption func(c *gzRoundtripper)
37
38 // TransportEnableZstd will send Zstandard as a compression option to the server.
39 // Enabled by default, but may be disabled if future problems arise.
40 func TransportEnableZstd(b bool) transportOption {
41 return func(c *gzRoundtripper) {
42 c.withZstd = b
43 }
44 }
45
46 // TransportEnableGzip will send Gzip as a compression option to the server.
47 // Enabled by default.
48 func TransportEnableGzip(b bool) transportOption {
49 return func(c *gzRoundtripper) {
50 c.withGzip = b
51 }
52 }
53
54 // TransportCustomEval will send the header of a response to a custom function.
55 // If the function returns false, the response will be returned as-is,
56 // Otherwise it will be decompressed based on Content-Encoding field, regardless
57 // of whether the transport added the encoding.
58 func TransportCustomEval(fn func(header http.Header) bool) transportOption {
59 return func(c *gzRoundtripper) {
60 c.customEval = fn
61 }
62 }
63
64 // TransportAlwaysDecompress will always decompress the response,
65 // regardless of whether we requested it or not.
66 // Default is false, which will pass compressed data through
67 // if we did not request compression.
68 func TransportAlwaysDecompress(enabled bool) transportOption {
69 return func(c *gzRoundtripper) {
70 c.alwaysDecomp = enabled
71 }
72 }
73
74 type gzRoundtripper struct {
75 parent http.RoundTripper
76 acceptEncoding string
77 withZstd, withGzip bool
78 alwaysDecomp bool
79 customEval func(header http.Header) bool
80 }
81
82 func (g *gzRoundtripper) RoundTrip(req *http.Request) (*http.Response, error) {
83 var requestedComp bool
84 if req.Header.Get("Accept-Encoding") == "" &&
85 req.Header.Get("Range") == "" &&
86 req.Method != "HEAD" {
87 // Request gzip only, not deflate. Deflate is ambiguous and
88 // not as universally supported anyway.
89 // See: https://zlib.net/zlib_faq.html#faq39
90 //
91 // Note that we don't request this for HEAD requests,
92 // due to a bug in nginx:
93 // https://trac.nginx.org/nginx/ticket/358
94 // https://golang.org/issue/5522
95 //
96 // We don't request gzip if the request is for a range, since
97 // auto-decoding a portion of a gzipped document will just fail
98 // anyway. See https://golang.org/issue/8923
99 requestedComp = len(g.acceptEncoding) > 0
100 req.Header.Set("Accept-Encoding", g.acceptEncoding)
101 }
102
103 resp, err := g.parent.RoundTrip(req)
104 if err != nil {
105 return resp, err
106 }
107 decompress := g.alwaysDecomp
108 if g.customEval != nil {
109 if !g.customEval(resp.Header) {
110 return resp, nil
111 }
112 decompress = true
113 } else {
114 if !requestedComp && !g.alwaysDecomp {
115 return resp, nil
116 }
117 }
118 // Decompress
119 if (decompress || g.withGzip) && asciiEqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
120 resp.Body = &gzipReader{body: resp.Body}
121 resp.Header.Del("Content-Encoding")
122 resp.Header.Del("Content-Length")
123 resp.ContentLength = -1
124 resp.Uncompressed = true
125 }
126 if (decompress || g.withZstd) && asciiEqualFold(resp.Header.Get("Content-Encoding"), "zstd") {
127 resp.Body = &zstdReader{body: resp.Body}
128 resp.Header.Del("Content-Encoding")
129 resp.Header.Del("Content-Length")
130 resp.ContentLength = -1
131 resp.Uncompressed = true
132 }
133
134 return resp, nil
135 }
136
137 var gzReaderPool sync.Pool
138
139 // gzipReader wraps a response body so it can lazily
140 // call gzip.NewReader on the first call to Read
141 type gzipReader struct {
142 body io.ReadCloser // underlying HTTP/1 response body framing
143 zr *gzip.Reader // lazily-initialized gzip reader
144 zerr error // any error from gzip.NewReader; sticky
145 }
146
147 func (gz *gzipReader) Read(p []byte) (n int, err error) {
148 if gz.zr == nil {
149 if gz.zerr == nil {
150 zr, ok := gzReaderPool.Get().(*gzip.Reader)
151 if ok {
152 gz.zr, gz.zerr = zr, zr.Reset(gz.body)
153 } else {
154 gz.zr, gz.zerr = gzip.NewReader(gz.body)
155 }
156 }
157 if gz.zerr != nil {
158 return 0, gz.zerr
159 }
160 }
161
162 return gz.zr.Read(p)
163 }
164
165 func (gz *gzipReader) Close() error {
166 if gz.zr != nil {
167 gzReaderPool.Put(gz.zr)
168 gz.zr = nil
169 }
170 return gz.body.Close()
171 }
172
173 // asciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t
174 // are equal, ASCII-case-insensitively.
175 func asciiEqualFold(s, t string) bool {
176 if len(s) != len(t) {
177 return false
178 }
179 for i := 0; i < len(s); i++ {
180 if lower(s[i]) != lower(t[i]) {
181 return false
182 }
183 }
184 return true
185 }
186
187 // lower returns the ASCII lowercase version of b.
188 func lower(b byte) byte {
189 if 'A' <= b && b <= 'Z' {
190 return b + ('a' - 'A')
191 }
192 return b
193 }
194
195 // zstdReaderPool pools zstd decoders.
196 var zstdReaderPool sync.Pool
197
198 // zstdReader wraps a response body so it can lazily
199 // call zstd.NewReader on the first call to Read
200 type zstdReader struct {
201 body io.ReadCloser // underlying HTTP/1 response body framing
202 zr *zstd.Decoder // lazily-initialized zstd reader
203 zerr error // any error from zstd.NewReader; sticky
204 }
205
206 func (zr *zstdReader) Read(p []byte) (n int, err error) {
207 if zr.zerr != nil {
208 return 0, zr.zerr
209 }
210 if zr.zr == nil {
211 reader, ok := zstdReaderPool.Get().(*zstd.Decoder)
212 if ok {
213 zr.zerr = reader.Reset(zr.body)
214 zr.zr = reader
215 } else {
216 zr.zr, zr.zerr = zstd.NewReader(zr.body, zstd.WithDecoderLowmem(true), zstd.WithDecoderMaxWindow(32<<20), zstd.WithDecoderConcurrency(1))
217 }
218 if zr.zerr != nil {
219 return 0, zr.zerr
220 }
221 }
222 n, err = zr.zr.Read(p)
223 if err != nil {
224 // Usually this will be io.EOF,
225 // stash the decoder and keep the error.
226 zr.zr.Reset(nil)
227 zstdReaderPool.Put(zr.zr)
228 zr.zr = nil
229 zr.zerr = err
230 }
231 return
232 }
233
234 func (zr *zstdReader) Close() error {
235 if zr.zr != nil {
236 zr.zr.Reset(nil)
237 zstdReaderPool.Put(zr.zr)
238 zr.zr = nil
239 }
240 return zr.body.Close()
241 }