Skip to content

Commit

Permalink
encode: ignore flushing until after first write
Browse files Browse the repository at this point in the history
The first write will determine if encoding has to be done and will add an Content-Encoding. Until then Flushing has to be delayed so the Content-Encoding header can be added before headers and status code is written. (A passthrough flush would write header and status code)
  • Loading branch information
ueffel committed Aug 31, 2021
1 parent f43fd6f commit bcd3520
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions modules/caddyhttp/encode/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ type responseWriter struct {
buf *bytes.Buffer
config *Encode
statusCode int
wroteHeader bool
}

// WriteHeader stores the status to write when the time comes
Expand All @@ -195,6 +196,17 @@ func (enc *Encode) Match(rw *responseWriter) bool {
return enc.Matcher.Match(rw.statusCode, rw.Header())
}

func (rw *responseWriter) Flush() {
if !rw.wroteHeader {
// flushing the underlying ResponseWriter will write header and status code
// but we need to delay that until we can determine if we must encode and
// therefore add the Content-Encoding header
// this happens in the first call to rw.Write
return
}
rw.ResponseWriterWrapper.Flush()
}

// Write writes to the response. If the response qualifies,
// it is encoded using the encoder, which is initialized
// if not done so already.
Expand Down Expand Up @@ -225,6 +237,7 @@ func (rw *responseWriter) Write(p []byte) (int, error) {
if rw.statusCode > 0 {
rw.ResponseWriter.WriteHeader(rw.statusCode)
rw.statusCode = 0
rw.wroteHeader = true
}

switch {
Expand Down Expand Up @@ -271,6 +284,7 @@ func (rw *responseWriter) Close() error {
// that rely on If-None-Match, for example
rw.ResponseWriter.WriteHeader(rw.statusCode)
rw.statusCode = 0
rw.wroteHeader = true
}
if rw.w != nil {
err2 := rw.w.Close()
Expand Down

0 comments on commit bcd3520

Please sign in to comment.