Skip to content

Commit

Permalink
Issue #300: GzipHandler should implement http.Hijacker
Browse files Browse the repository at this point in the history
  • Loading branch information
magiconair committed May 24, 2017
1 parent b90b44c commit 538e500
Showing 1 changed file with 28 additions and 11 deletions.
39 changes: 28 additions & 11 deletions proxy/gzip/gzip_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
package gzip

import (
"bufio"
"compress/gzip"
"errors"
"io"
"net"
"net/http"
"regexp"
"strings"
Expand All @@ -29,21 +32,35 @@ var gzipWriterPool = sync.Pool{
New: func() interface{} { return gzip.NewWriter(nil) },
}

type gzipHandler struct {
h http.Handler
contentTypes *regexp.Regexp
}

func (h *gzipHandler) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hj, ok := h.h.(http.Hijacker); ok {
return hj.Hijack()
}
return nil, nil, errors.New("not a Hijacker")
}

func (h *gzipHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Add(headerVary, headerAcceptEncoding)

if acceptsGzip(r) {
gzWriter := NewGzipResponseWriter(w, h.contentTypes)
defer gzWriter.Close()
h.h.ServeHTTP(gzWriter, r)
} else {
h.h.ServeHTTP(w, r)
}
}

// NewGzipHandler wraps an existing handler to transparently gzip the response
// body if the client supports it (via the Accept-Encoding header) and the
// response Content-Type matches the contentTypes expression.
func NewGzipHandler(h http.Handler, contentTypes *regexp.Regexp) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(headerVary, headerAcceptEncoding)

if acceptsGzip(r) {
gzWriter := NewGzipResponseWriter(w, contentTypes)
defer gzWriter.Close()
h.ServeHTTP(gzWriter, r)
} else {
h.ServeHTTP(w, r)
}
})
return &gzipHandler{h, contentTypes}
}

type GzipResponseWriter struct {
Expand Down

0 comments on commit 538e500

Please sign in to comment.