Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current response length from a http.ResponseWriter

Tags:

go

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.

like image 321
the system Avatar asked Dec 20 '12 19:12

the system


1 Answers

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.

like image 160
nemo Avatar answered Oct 20 '22 15:10

nemo