package etag import ( "bytes" "net/http" "strings" ) // responseWriter is a custom implementation of http.ResponseWriter that buffers the response body // and stores some additional information to facilitate ETag processing. type responseWriter struct { http.ResponseWriter buf bytes.Buffer // maxBufSize is the maximum size of buf in bytes maxBufSize int // Marks whether the response should be passed through without ETag processing (e.g., for streamed responses). passthrough bool // delegate forwards future writes directly to the underlying writer. delegate bool rc *http.ResponseController statusCode int wroteHeader bool } // newResponseWriter creates a new instance of responseWriter that wraps the provided http.ResponseWriter. func newResponseWriter(w http.ResponseWriter, maxBufSize int) *responseWriter { return &responseWriter{ ResponseWriter: w, maxBufSize: maxBufSize, rc: http.NewResponseController(w), statusCode: http.StatusOK, // Default to 200 OK } } func (rw *responseWriter) Flush() { if rw.delegate { _ = rw.rc.Flush() return } // When `Flush` is called, it indicates that the response is being streamed. // In this case, we should enable passthrough mode. if !rw.passthrough { _ = rw.enablePassthrough() } _ = rw.rc.Flush() } func (rw *responseWriter) Write(b []byte) (int, error) { if rw.delegate || rw.passthrough { return rw.ResponseWriter.Write(b) } if len(b) > rw.maxBufSize-rw.buf.Len() { if err := rw.enablePassthrough(); err != nil { return 0, err } return rw.ResponseWriter.Write(b) } return rw.buf.Write(b) } func (rw *responseWriter) WriteHeader(statusCode int) { // If the standard WriteHeader called multiple times, it uses the first one and ignores subsequent calls. // We should respect that behavior and not change the status code if it's already been set. if rw.wroteHeader { return } if rw.delegate { rw.statusCode = statusCode rw.wroteHeader = true rw.ResponseWriter.WriteHeader(statusCode) return } rw.statusCode = statusCode contentType := rw.Header().Get("Content-Type") if strings.HasPrefix(contentType, "text/event-stream") { _ = rw.enablePassthrough() } rw.wroteHeader = true } func (rw *responseWriter) enablePassthrough() error { if rw.passthrough { return nil } rw.passthrough = true rw.ResponseWriter.WriteHeader(rw.statusCode) if rw.buf.Len() > 0 { _, err := rw.ResponseWriter.Write(rw.buf.Bytes()) return err } return nil }