forked from martini-contrib/gzip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgzip.go
67 lines (53 loc) · 1.5 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
package gzip
import (
"bufio"
"compress/gzip"
"fmt"
"net"
"net/http"
"strings"
"github.com/go-martini/martini"
)
const (
HeaderAcceptEncoding = "Accept-Encoding"
HeaderContentEncoding = "Content-Encoding"
HeaderContentLength = "Content-Length"
HeaderContentType = "Content-Type"
HeaderVary = "Vary"
)
var serveGzip = func(w http.ResponseWriter, r *http.Request, c martini.Context) {
if !strings.Contains(r.Header.Get(HeaderAcceptEncoding), "gzip") {
return
}
headers := w.Header()
headers.Set(HeaderContentEncoding, "gzip")
headers.Set(HeaderVary, HeaderAcceptEncoding)
gz := gzip.NewWriter(w)
defer gz.Close()
gzw := gzipResponseWriter{gz, w.(martini.ResponseWriter)}
c.MapTo(gzw, (*http.ResponseWriter)(nil))
c.Next()
// delete content length after we know we have been written to
gzw.Header().Del("Content-Length")
}
// All returns a Handler that adds gzip compression to all requests
func All() martini.Handler {
return serveGzip
}
type gzipResponseWriter struct {
w *gzip.Writer
martini.ResponseWriter
}
func (grw gzipResponseWriter) Write(p []byte) (int, error) {
if len(grw.Header().Get(HeaderContentType)) == 0 {
grw.Header().Set(HeaderContentType, http.DetectContentType(p))
}
return grw.w.Write(p)
}
func (grw gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := grw.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("the ResponseWriter doesn't support the Hijacker interface")
}
return hijacker.Hijack()
}