Merge pull request #29 from dimitor115/master

Add gzip handling
This commit is contained in:
Pierre Zemb 2020-03-01 11:41:05 +01:00 committed by GitHub
commit 84a438493d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

36
main.go
View file

@ -4,12 +4,16 @@
package main
import (
"compress/gzip"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"sync"
)
var (
@ -40,6 +44,27 @@ func parseHeaderFlag(headerFlag string) (string, string) {
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() {
flag.Parse()
@ -85,7 +110,18 @@ func main() {
fileServer := handler
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(header, headerValue)
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 {
log.Println("appendHeader misconfigured; ignoring.")