diff --git a/server/gzipresponsewriter.go b/server/gzipresponsewriter.go deleted file mode 100755 index c33a8a4..0000000 --- a/server/gzipresponsewriter.go +++ /dev/null @@ -1,49 +0,0 @@ -package server - -import ( - "compress/gzip" - "fmt" - "net/http" - "strings" -) - -type GZipResponseWriter struct { - w http.ResponseWriter - gz *gzip.Writer -} - -func NewGZipResponseWriter(w http.ResponseWriter) *GZipResponseWriter { - w.Header().Add("Content-Type", "text/html") - w.Header().Add("Content-Encoding", "gzip") - return &GZipResponseWriter{ - w: w, - gz: gzip.NewWriter(w), - } -} - -func (gz *GZipResponseWriter) Header() http.Header { - return gz.w.Header() -} - -func (gz *GZipResponseWriter) WriteHeader(statusCode int) { - gz.w.WriteHeader(statusCode) -} - -func (gz *GZipResponseWriter) Write(b []byte) (int, error) { - return gz.gz.Write(b) -} - -func (gz *GZipResponseWriter) Close() error { - return gz.gz.Close() -} - -func (s *Server) gzip(h http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if encoding, _ := r.Header["Accept-Encoding"]; strings.Contains(fmt.Sprint(encoding), "gzip") { - gz := NewGZipResponseWriter(w) - defer gz.Close() - w = gz - } - h(w, r) - } -} diff --git a/server/gzipresponsewriter_test.go b/server/gzipresponsewriter_test.go deleted file mode 100755 index cf89d00..0000000 --- a/server/gzipresponsewriter_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package server - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" -) - -func TestGZipResponseWriter(t *testing.T) { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gz := NewGZipResponseWriter(w) - defer gz.Close() - fmt.Fprintln(gz, "Hello world") - })) - defer s.Close() - - req := httptest.NewRequest("GET", s.URL, nil) - req.RequestURI = "" - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - t.Fatal(resp.StatusCode) - } - if b, err := ioutil.ReadAll(resp.Body); err != nil { - t.Fatal(err) - } else if s := string(b); s != "Hello world\n" { - t.Fatalf("%q", s) - } -} diff --git a/server/routes.go b/server/routes.go index c9bde69..bf31d62 100755 --- a/server/routes.go +++ b/server/routes.go @@ -2,8 +2,10 @@ package server import ( "fmt" + "local/gziphttp" "local/router" "net/http" + "path/filepath" ) func (s *Server) Routes() error { @@ -54,3 +56,17 @@ func (s *Server) root(w http.ResponseWriter, r *http.Request) { r.URL.Path = "/notes" http.Redirect(w, r, r.URL.String(), http.StatusPermanentRedirect) } + +func (s *Server) gzip(h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if gziphttp.Can(r) { + gz := gziphttp.New(w) + defer gz.Close() + w = gz + } + if filepath.Ext(r.URL.Path) == ".css" { + w.Header().Set("Content-Type", "text/css; charset=utf-8") + } + h(w, r) + } +}