Given a http.ResponseWriter
that has had some number of .Write()
s done to it, can the current accumulated length of the response be obtained directly?
I'm pretty sure this could be done with a Hijack
conversion, but I'd like to know if it can be done directly.
Even if you'd know what you get, underlying the http.ResponseWriter
interface, the chances are low, that there is something usable. If you look closer at the struct you get using the standard ServeHTTP
of the http package, you'll see that there's no way to get to the length of the buffer but hijacking it.
What you can do alternatively, is shadowing the writer:
type ResponseWriterWithLength struct {
http.ResponseWriter
length int
}
func (w *ResponseWriterWithLength) Write(b []byte) (n int, err error) {
n, err = w.ResponseWriter.Write(b)
w.length += n
return
}
func (w *ResponseWriterWithLength) Length() int {
return w.length
}
func MyServant(w http.ResponseWriter, r *http.Request) {
lengthWriter := &ResponseWriterWithLength{w, 0}
}
You might even want to write your own version of http.Server
, which serves the ResponseWriterWithLength
by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With