Skip to content

Commit

Permalink
Fix Content-Type detection w/ buffered response
Browse files Browse the repository at this point in the history
  • Loading branch information
tmthrgd committed Apr 4, 2017
1 parent 6c46a54 commit 4324668
Showing 1 changed file with 30 additions and 11 deletions.
41 changes: 30 additions & 11 deletions gzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,6 @@ type responseWriter struct {

// Write appends data to the gzip writer.
func (w *responseWriter) Write(b []byte) (int, error) {
h := w.Header()

// If content type is not set.
if _, ok := h["Content-Type"]; !ok {
// It infer it from the uncompressed body.
h["Content-Type"] = []string{http.DetectContentType(b)}
}

// GZIP responseWriter is initialized. Use the GZIP
// responseWriter.
if w.gw != nil {
Expand All @@ -58,11 +50,15 @@ func (w *responseWriter) Write(b []byte) (int, error) {
// responseWriter.
w.buf = append(w.buf, b...)
return len(b), nil
} else if err := w.startGzip(); err != nil {
}

w.inferContentType(b)

if err := w.startGzip(); err != nil {
return 0, err
} else {
return w.gw.Write(b)
}

return w.gw.Write(b)
}

// startGzip initialize any GZIP specific informations.
Expand Down Expand Up @@ -101,6 +97,29 @@ func (w *responseWriter) startGzip() error {
return err
}

func (w *responseWriter) inferContentType(b []byte) {
h := w.Header()

// If content type is not set.
if _, ok := h["Content-Type"]; ok {
return
}

if len(w.buf) != 0 {
const sniffLen = 512
if len(w.buf) >= sniffLen {
b = w.buf
} else if len(w.buf)+len(b) > sniffLen {
b = append(w.buf, b[:sniffLen-len(w.buf)]...)
} else {
b = append(w.buf, b...)
}
}

// It infer it from the uncompressed body.
h["Content-Type"] = []string{http.DetectContentType(b)}
}

// WriteHeader just saves the response code until close or
// GZIP effective writes.
func (w *responseWriter) WriteHeader(code int) {
Expand Down

0 comments on commit 4324668

Please sign in to comment.