From 34a3fe426b33a63f2d8e02d4a70c88f137fa5410 Mon Sep 17 00:00:00 2001 From: Frédéric Guillot Date: Fri, 6 Jul 2018 20:39:28 -0700 Subject: Compress HTML responses to Gzip/Deflate if supported by browser --- http/response/html/html.go | 5 +++-- http/response/response.go | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) (limited to 'http') diff --git a/http/response/html/html.go b/http/response/html/html.go index 4f605e8..a17ce04 100644 --- a/http/response/html/html.go +++ b/http/response/html/html.go @@ -7,13 +7,14 @@ package html import ( "net/http" + "github.com/miniflux/miniflux/http/response" "github.com/miniflux/miniflux/logger" ) // OK writes a standard HTML response. -func OK(w http.ResponseWriter, b []byte) { +func OK(w http.ResponseWriter, r *http.Request, b []byte) { w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Write(b) + response.Compress(w, r, b) } // ServerError sends a 500 error to the browser. diff --git a/http/response/response.go b/http/response/response.go index 066d061..c5ae3fa 100644 --- a/http/response/response.go +++ b/http/response/response.go @@ -5,7 +5,10 @@ package response import ( + "compress/flate" + "compress/gzip" "net/http" + "strings" "time" ) @@ -32,3 +35,23 @@ func Cache(w http.ResponseWriter, r *http.Request, mimeType, etag string, conten w.Write(content) } } + +// Compress the response sent to the browser. +func Compress(w http.ResponseWriter, r *http.Request, data []byte) { + acceptEncoding := r.Header.Get("Accept-Encoding") + + switch { + case strings.Contains(acceptEncoding, "gzip"): + w.Header().Set("Content-Encoding", "gzip") + gzipWriter := gzip.NewWriter(w) + defer gzipWriter.Close() + gzipWriter.Write(data) + case strings.Contains(acceptEncoding, "deflate"): + w.Header().Set("Content-Encoding", "deflate") + flateWriter, _ := flate.NewWriter(w, -1) + defer flateWriter.Close() + flateWriter.Write(data) + default: + w.Write(data) + } +} -- cgit v1.2.3