-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic.go
362 lines (319 loc) · 8.73 KB
/
dynamic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// Package gowebcompress applies top compression hueristics to
// offer a dynamic (for APIs) and Static http middleware to
// accelerate your server.
package gowebcompress
import (
"compress/gzip"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path"
"strings"
"sync"
"time"
"github.com/itchio/go-brotli/enc"
)
var DynamicLevels = Levels{2, 2}
var StaticLevels = Levels{6, 4}
const (
none = iota
gzType = iota
brType = iota
)
type Levels struct {
Gzip int
Brotli int
}
type outBuf struct {
b []byte
req *http.Request
http.ResponseWriter // For APIs only.
compressor io.WriteCloser
output io.Writer
cmpType int
Errors []error
}
var bufpool = &sync.Pool{
New: func() interface{} {
return make([]byte, 0, 1024)
},
}
// Middleware for compression supporting Brotoli & Gzip.
// Uses a static-compiled Brotoli library (no external dep). Have a compiler ready.
// Optimized for low CPU usage: 80kb/ms today, or change DynamicLevels / StaticLevels.
func Middleware(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
buf, closer := Handler(w, req)
defer closer()
handler.ServeHTTP(buf, req)
})
}
// Handler makes it easy for wrapping for custom routers (ex: Gin)
func Handler(w http.ResponseWriter, req *http.Request) (newWriter http.ResponseWriter, complete func()) {
buf := &outBuf{nil, req, w, nil, w, none, nil}
return buf, func() {
defer func() {
if buf.b != nil {
bufpool.Put(buf.b[:0])
}
}()
if buf.compressor != nil { // If there's data in compressor, finalize it
err := buf.compressor.Close()
if err != nil {
buf.Errors = append(buf.Errors, err)
}
}
if _, err := buf.output.Write(buf.b); err != nil {
buf.Errors = append(buf.Errors, err)
return
}
if c, ok := buf.compressor.(*fsCache); ok { // first compress, write MIME
c.WriteMIME(buf.Header().Get("content-type"))
}
}
}
func (o *outBuf) Write(b []byte) (i int, err error) {
if o.compressor == nil {
if len(o.b)+len(b) < 1024 { // under 1024 bytes
if o.b == nil {
o.b = bufpool.Get().([]byte)[:0]
}
o.b = append(o.b, b...) // Copy. Never keep "b"
return len(b), nil
}
amnt, err := o.compressorCatchup(DynamicLevels, nil)
if err != nil {
return amnt, err
}
}
return o.compressor.Write(b)
}
func (o *outBuf) compressorCatchup(l Levels, cacher *fsCache) (int, error) {
var err error
o.compressor, o.cmpType, err = o.getCompressWriter(o.req, o.output, l, cacher)
if err != nil || len(o.b) == 0 {
return 0, err
}
return o.compressor.Write(o.b)
}
func (o *outBuf) getCompressWriter(req *http.Request, output io.Writer, l Levels, cacher *fsCache) (input io.WriteCloser, encoding int, err error) {
encoding = o.shouldCompress()
input, err = makeCompressor(encoding, o.ResponseWriter, l, cacher)
return input, encoding, err
}
func makeCompressor(encoding int, w http.ResponseWriter, levels Levels, cacher *fsCache) (input io.WriteCloser, err error) {
var cmp io.WriteCloser
h := w.Header()
var out io.Writer = w
if cacher != nil {
out = io.MultiWriter(cacher.disk, w)
}
switch encoding {
case gzType:
cmp, err = gzip.NewWriterLevel(out, levels.Gzip)
if err != nil {
return nil, err
}
headersFor(h, encoding)
case brType:
var brotliParam = &enc.BrotliWriterOptions{Quality: levels.Brotli}
cmp = enc.NewBrotliWriter(out, brotliParam)
headersFor(h, encoding)
default:
cmp = &fakecloser{out} // closer may be double-called
}
h.Set("Vary", "Accept-Encoding") // Tells CDNs to respect Accept-Encoding
if cacher != nil {
cacher.wc = cmp
return cacher, nil
}
return cmp, nil
}
var ceString = map[int]string{
gzType: "gzip",
brType: "br",
none: "identity",
}
func headersFor(h http.Header, encoding int) {
delete(h, "content-length")
delete(h, "Content-Length")
ce := "Content-Encoding"
if h.Get("Content-Range") != "" {
ce = "TE"
}
h.Set(ce, ceString[encoding])
}
type fakecloser struct {
io.Writer
}
func (f *fakecloser) Close() error { return nil }
func (o *outBuf) shouldCompress() int {
// pprof acts badly
p := o.req.URL.Path
if len(p) > 11 && p[:12] == "/debug/pprof" {
return none
}
// Can we prove it's already compressed?
if alreadyCompressed(o.ResponseWriter.Header().Get("Content-Type")) {
return none
}
// The browser wants...
return browserWants(o.req)
}
func browserWants(r *http.Request) int {
ae := r.Header.Get("Accept-Encoding")
if strings.Contains(ae, "br") && (r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https") {
return brType
}
if strings.Contains(ae, "gzip") {
return gzType
}
return none
}
func alreadyCompressed(mime string) bool {
if len(mime) >= 5 {
ctStart := mime[:6]
if ctStart == "image/" {
t := mime[6:]
if t != "gif" && t != "png" {
return true
}
} else if ctStart == "video/" || ctStart == "audio/" {
return true
} else if len(mime) >= 9 && mime[:9] == "font/woff" {
return true
}
}
return false
}
// fsCache will cache if we have a place to cache.
type fsCache struct {
disk io.WriteCloser
wc io.WriteCloser
mimefile io.WriteCloser
}
func (m *fsCache) Write(b []byte) (i int, err error) {
return m.wc.Write(b)
}
func (m *fsCache) Close() error {
m.wc.Close() // ignore gzip errors because bytes are already written.
return m.disk.Close()
}
func (m *fsCache) WriteMIME(s string) {
m.mimefile.Write([]byte(s))
m.mimefile.Close()
}
func (o *outBuf) FS(sys fs.FS, origPath string, creat CreateFile, staticBase string) (handled bool) {
if o.req.Method != http.MethodGet {
return false // don't cache
}
origFullPath := path.Join(staticBase, origPath)
if !strings.HasPrefix(origFullPath, staticBase) {
o.Errors = append(o.Errors, errors.New("Illegal path: "+origFullPath))
return false // don't share something outside the base.
}
st, ok := sys.(fs.StatFS)
if !ok || st == nil {
o.Errors = append(o.Errors, fmt.Errorf("isn't statfs"))
}
o.cmpType = o.shouldCompress()
dest := origFullPath + "." + ceString[o.cmpType]
if o.cmpType == none {
return false
}
if compressedStat, err := st.Stat(dest); err == nil {
origStat, err := st.Stat(origFullPath)
if err != nil || compressedStat.IsDir() || origStat.IsDir() {
return false // no file. No future.
}
if h := o.req.Header.Get("if-modified-since"); len(h) > 0 {
if t, err := time.Parse(time.RFC1123, h); err == nil {
if origStat.ModTime().Before(t) {
o.ResponseWriter.WriteHeader(304)
return true
}
}
}
// Compare timestamps orig vs disk. if newer, write & handled.
if compressedStat.ModTime().After(origStat.ModTime()) {
mimepath := origFullPath + ".mime"
if dest[0] == '/' {
dest = dest[1:]
mimepath = mimepath[1:]
}
f, err := st.Open(dest)
if err != nil {
o.Errors = append(o.Errors, fmt.Errorf("open err: %w", err))
return false
}
defer f.Close()
fm, err := st.Open(mimepath)
if err != nil {
o.Errors = append(o.Errors, fmt.Errorf("open err: %w", err))
return false
}
defer fm.Close()
b, err := io.ReadAll(fm)
if err != nil {
o.Errors = append(o.Errors, fmt.Errorf("fm read err: %w", err))
return false
}
h := o.ResponseWriter.Header()
h.Add("content-type", string(b))
headersFor(h, o.cmpType)
_, err = io.Copy(o.ResponseWriter, f)
if err != nil {
o.Errors = append(o.Errors, fmt.Errorf("Copy err: %w", err))
return true
}
return true
}
}
if o.compressor == nil /* No bytes written */ {
outfile, err := creat(dest)
if err != nil {
o.Errors = append(o.Errors, fmt.Errorf("can't create file: %w", err))
return
}
mimefile, err := creat(origFullPath + ".mime")
if err != nil {
o.Errors = append(o.Errors, fmt.Errorf("can't create file: %w", err))
return
}
_, err = o.compressorCatchup(StaticLevels, &fsCache{disk: outfile, mimefile: mimefile})
if err != nil {
o.Errors = append(o.Errors, err)
}
}
return false
}
type CacheOpts struct {
fs.FS
CreateFile
BasePath string
}
// FS is a convenience function for informing the cacher
// that a static file is being served and the compressed contents
// can be cached there.
// It requires the Middleware to have ran & fs must support StatFS.
// Use in handler (for static/foo.txt):
// if gowebcompress.FS(w, os.DirFS("/"), os.Create, "static/foo.txt") {
// return; // Bytes sent from Disk Cache
// }
// serveFile("static/foo.txt")
func FS(w io.Writer, opts CacheOpts, origPath string) (handled bool) {
return w.(*outBuf).FS(opts.FS, origPath, opts.CreateFile, opts.BasePath)
}
type CreateFile func(path string) (io.WriteCloser, error)
type CacheInfo interface {
GetErrors() []error
}
func (o *outBuf) GetErrors() []error {
return o.Errors
}
func OSCreate(abspath string) (io.WriteCloser, error) {
return os.Create(abspath)
}