forked from gin-contrib/gzip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gzip.go
76 lines (61 loc) · 1.71 KB
/
gzip.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
package gzip
import (
"bytes"
"compress/gzip"
"github.com/gin-gonic/gin"
)
const (
BestCompression = gzip.BestCompression
BestSpeed = gzip.BestSpeed
DefaultCompression = gzip.DefaultCompression
NoCompression = gzip.NoCompression
)
func Gzip(level int, options ...Option) gin.HandlerFunc {
return newGzipHandler(level, options...).Handle
}
type gzipWriter struct {
gin.ResponseWriter
writer *gzip.Writer
buffer bytes.Buffer
minLength int
compress bool
}
func (g *gzipWriter) WriteString(s string) (int, error) {
g.Header().Del("Content-Length")
return g.writer.Write([]byte(s))
}
func (g *gzipWriter) Write(data []byte) (int, error) {
// If the first chunk of data is already bigger than the minimum size,
// set the headers and write directly to the gz writer
if !g.compress && len(data) >= g.minLength {
g.ResponseWriter.Header().Set("Content-Encoding", "gzip")
g.ResponseWriter.Header().Set("Vary", "Accept-Encoding")
g.compress = true
}
if g.compress {
// Write the data into the gz writer
return g.writer.Write(data)
}
// Write the data into a buffer
w, err := g.buffer.Write(data)
if err != nil {
return w, err
}
// If the buffer is bigger than the minimum size, set the headers and write
// the buffered data into the gz writer
if g.buffer.Len() >= g.minLength {
g.ResponseWriter.Header().Set("Content-Encoding", "gzip")
g.ResponseWriter.Header().Set("Vary", "Accept-Encoding")
w, err = g.writer.Write(g.buffer.Bytes())
if err != nil {
return w, err
}
g.compress = true
}
return w, err
}
// Fix: https://github.com/mholt/caddy/issues/38
func (g *gzipWriter) WriteHeader(code int) {
g.Header().Del("Content-Length")
g.ResponseWriter.WriteHeader(code)
}