Skip to content

Commit

Permalink
Allow access to internal ResponseWriter in gzhttp handler (#799)
Browse files Browse the repository at this point in the history
Sometimes users will want to use the `http.Flusher`, or `http.Hijacker`, etc. interfaces from an `http.ResponseWriter`, which `gzhttp.ResponseWriter` does not implement but the underlying one does.

It is common to provide an `Unwrap` function to access it, for example the standard library expects that (although I didn't find any official documentation on it). See [http.ResponseController](https://cs.opensource.google/go/go/+/refs/tags/go1.20.2:src/net/http/responsecontroller.go;l=41-43) for example.
  • Loading branch information
jgimenez authored Apr 5, 2023
1 parent 9243a1f commit 3c61d32
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions gzhttp/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ func (w *GzipResponseWriter) Write(b []byte) (int, error) {
return len(b), nil
}

func (w *GzipResponseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}

var castagnoliTable = crc32.MakeTable(crc32.Castagnoli)

// startGzip initializes a GZIP writer and writes the buffer.
Expand Down Expand Up @@ -919,6 +923,10 @@ func atoi(s string) (int, bool) {
return int(i64), err == nil
}

type unwrapper interface {
Unwrap() http.ResponseWriter
}

// newNoGzipResponseWriter will return a response writer that
// cleans up compression artifacts.
// Depending on whether http.Hijacker is supported the returned will as well.
Expand All @@ -929,10 +937,12 @@ func newNoGzipResponseWriter(w http.ResponseWriter) http.ResponseWriter {
http.ResponseWriter
http.Hijacker
http.Flusher
unwrapper
}{
ResponseWriter: n,
Hijacker: hj,
Flusher: n,
unwrapper: n,
}
return x
}
Expand Down Expand Up @@ -982,3 +992,7 @@ func (n *NoGzipResponseWriter) WriteHeader(statusCode int) {
}
n.ResponseWriter.WriteHeader(statusCode)
}

func (n *NoGzipResponseWriter) Unwrap() http.ResponseWriter {
return n.ResponseWriter
}

0 comments on commit 3c61d32

Please sign in to comment.