Add gzip handling

This commit is contained in:
Maciej Kopeć 2020-02-26 21:39:06 +01:00
parent 20aeab6b06
commit 7278807b24

38
main.go
View file

@ -4,12 +4,16 @@
package main package main
import ( import (
"compress/gzip"
"flag" "flag"
"fmt" "fmt"
"io"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"sync"
) )
var ( var (
@ -40,6 +44,27 @@ func parseHeaderFlag(headerFlag string) (string, string) {
return pieces[0], pieces[1] return pieces[0], pieces[1]
} }
var gzPool = sync.Pool{
New: func() interface{} {
w := gzip.NewWriter(ioutil.Discard)
return w
},
}
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w *gzipResponseWriter) WriteHeader(status int) {
w.Header().Del("Content-Length")
w.ResponseWriter.WriteHeader(status)
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func main() { func main() {
flag.Parse() flag.Parse()
@ -85,7 +110,18 @@ func main() {
fileServer := handler fileServer := handler
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(header, headerValue) w.Header().Set(header, headerValue)
fileServer.ServeHTTP(w, r) if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
fileServer.ServeHTTP(w, r)
} else {
w.Header().Set("Content-Encoding", "gzip")
gz := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
gz.Reset(w)
defer gz.Close()
fileServer.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
}
}) })
} else { } else {
log.Println("appendHeader misconfigured; ignoring.") log.Println("appendHeader misconfigured; ignoring.")