-
Notifications
You must be signed in to change notification settings - Fork 53
/
gzip.go
51 lines (44 loc) · 979 Bytes
/
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
/*
* @Author: seekwe
* @Date: 2019-06-06 19:23:27
* @Last Modified by: seekwe
* @Last Modified time: 2019-06-06 19:35:46
*/
package gzip
import (
"bufio"
"compress/gzip"
"io"
"net"
"net/http"
"strings"
"github.com/sohaha/zlsgo/znet"
)
func New(level ...int) znet.HandlerFunc {
gzipLevel := 7
if len(level) > 0 {
gzipLevel = level[0]
}
return func(c *znet.Context) {
if !strings.Contains(c.GetHeader("Accept-Encoding"), "gzip") {
c.Next()
} else {
c.SetHeader("Content-Encoding", "gzip")
w := c.Writer
gw, _ := gzip.NewWriterLevel(w, gzipLevel)
defer gw.Close()
c.Writer = &gzipResponseWriter{Writer: gw, ResponseWriter: w}
c.Next()
}
}
}
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.ResponseWriter.(http.Hijacker).Hijack()
}