forked from etix/mirrorbits
/
gzip.go
41 lines (36 loc) · 999 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
// Copyright (c) 2014 Ludovic Fauvet
// Licensed under the MIT license
package main
import (
"github.com/youtube/vitess/go/cgzip"
"io"
"net/http"
"strings"
)
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
typeGuessed bool
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if !w.typeGuessed {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
w.typeGuessed = true
}
return w.Writer.Write(b)
}
// NewGzipHandler is an HTTP handler used to compress responses if supported by the client
func NewGzipHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !GetConfig().Gzip || !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
fn(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz, _ := cgzip.NewWriterLevel(w, cgzip.Z_BEST_SPEED)
defer gz.Close()
fn(&gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
}
}