Debian Codegraph @

http/gzip.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package http
5
6 import (
7 "io"
8 "net/http"
9 "strings"
10
11 . "github.com/etix/mirrorbits/config"
12 "github.com/youtube/vitess/go/cgzip"
13 )
14
15 type gzipResponseWriter struct {
16 io.Writer
17 http.ResponseWriter
18 typeGuessed bool
19 }
20
21 func (w *gzipResponseWriter) Write(b []byte) (int, error) {
22 if !w.typeGuessed {
23 if w.Header().Get("Content-Type") == "" {
24 w.Header().Set("Content-Type", http.DetectContentType(b))
25 }
26 w.typeGuessed = true
27 }
28 return w.Writer.Write(b)
29 }
30
31 // NewGzipHandler is an HTTP handler used to compress responses if supported by the client
32 func NewGzipHandler(fn http.HandlerFunc) http.HandlerFunc {
33 return func(w http.ResponseWriter, r *http.Request) {
34 if !GetConfig().Gzip || !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
35 fn(w, r)
36 return
37 }
38 w.Header().Set("Content-Encoding", "gzip")
39 gz, _ := cgzip.NewWriterLevel(w, cgzip.Z_BEST_SPEED)
40 defer gz.Close()
41 fn(&gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
42 }
43 }