2020-07-21 22:06:15 +02:00
|
|
|
package terminal
|
2020-07-01 01:26:16 -04:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"compress/gzip"
|
|
|
|
|
"io"
|
|
|
|
|
"net/http"
|
|
|
|
|
"strings"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type gzipResponseWriter struct {
|
|
|
|
|
io.Writer
|
|
|
|
|
http.ResponseWriter
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Use the Writer part of gzipResponseWriter to write the output.
|
|
|
|
|
|
|
|
|
|
func (w gzipResponseWriter) Write(b []byte) (int, error) {
|
|
|
|
|
return w.Writer.Write(b)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func makeGzipHandler(handler http.HandlerFunc) http.HandlerFunc {
|
|
|
|
|
return func(resp http.ResponseWriter, req *http.Request) {
|
|
|
|
|
// Check if the client can accept the gzip encoding.
|
2025-12-09 15:57:14 +00:00
|
|
|
isGzipEncoding := strings.Contains(
|
|
|
|
|
req.Header.Get("Accept-Encoding"), "gzip",
|
|
|
|
|
)
|
|
|
|
|
if !isGzipEncoding {
|
2020-07-01 01:26:16 -04:00
|
|
|
// The client cannot accept it, so return the output
|
|
|
|
|
// uncompressed.
|
|
|
|
|
handler(resp, req)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
// Set the HTTP header indicating encoding.
|
|
|
|
|
resp.Header().Set("Content-Encoding", "gzip")
|
|
|
|
|
gzipWriter := gzip.NewWriter(resp)
|
|
|
|
|
defer gzipWriter.Close()
|
2025-12-09 15:57:14 +00:00
|
|
|
gzipRespWriter := gzipResponseWriter{
|
|
|
|
|
Writer: gzipWriter, ResponseWriter: resp,
|
|
|
|
|
}
|
|
|
|
|
handler(gzipRespWriter, req)
|
2020-07-01 01:26:16 -04:00
|
|
|
}
|
|
|
|
|
}
|