Commit e283af4d authored by Matt Holt's avatar Matt Holt

Merge pull request #502 from abiosoft/gzip-fix

gzip: Fix for wrong content-type when templates is used.
parents 8a6c778c 12cd2d52
...@@ -121,12 +121,12 @@ func (w *gzipResponseWriter) WriteHeader(code int) { ...@@ -121,12 +121,12 @@ func (w *gzipResponseWriter) WriteHeader(code int) {
// Write wraps the underlying Write method to do compression. // Write wraps the underlying Write method to do compression.
func (w *gzipResponseWriter) Write(b []byte) (int, error) { func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if !w.statusCodeWritten {
w.WriteHeader(http.StatusOK)
}
if w.Header().Get("Content-Type") == "" { if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b)) w.Header().Set("Content-Type", http.DetectContentType(b))
} }
if !w.statusCodeWritten {
w.WriteHeader(http.StatusOK)
}
n, err := w.Writer.Write(b) n, err := w.Writer.Write(b)
return n, err return n, err
} }
...@@ -2,8 +2,10 @@ package gzip ...@@ -2,8 +2,10 @@ package gzip
import ( import (
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings"
"testing" "testing"
"github.com/mholt/caddy/middleware" "github.com/mholt/caddy/middleware"
...@@ -80,7 +82,16 @@ func TestGzipHandler(t *testing.T) { ...@@ -80,7 +82,16 @@ func TestGzipHandler(t *testing.T) {
func nextFunc(shouldGzip bool) middleware.Handler { func nextFunc(shouldGzip bool) middleware.Handler {
return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) { return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
w.Write([]byte("test"))
// write a relatively large text file
b, err := ioutil.ReadFile("testdata/test.txt")
if err != nil {
return 500, err
}
if _, err := w.Write(b); err != nil {
return 500, err
}
if shouldGzip { if shouldGzip {
if r.Header.Get("Accept-Encoding") != "" { if r.Header.Get("Accept-Encoding") != "" {
return 0, fmt.Errorf("Accept-Encoding header not expected") return 0, fmt.Errorf("Accept-Encoding header not expected")
...@@ -94,6 +105,9 @@ func nextFunc(shouldGzip bool) middleware.Handler { ...@@ -94,6 +105,9 @@ func nextFunc(shouldGzip bool) middleware.Handler {
if _, ok := w.(*gzipResponseWriter); !ok { if _, ok := w.(*gzipResponseWriter); !ok {
return 0, fmt.Errorf("ResponseWriter should be gzipResponseWriter, found %T", w) return 0, fmt.Errorf("ResponseWriter should be gzipResponseWriter, found %T", w)
} }
if strings.Contains(w.Header().Get("Content-Type"), "application/x-gzip") {
return 0, fmt.Errorf("Content type should not be gzip.")
}
return 0, nil return 0, nil
} }
if r.Header.Get("Accept-Encoding") == "" { if r.Header.Get("Accept-Encoding") == "" {
......
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment