http.ResponseWriter Content-Length

3,494 views
Skip to first unread message

yourcomputerpal

unread,
Dec 19, 2011, 1:34:32 PM12/19/11
to golang-nuts
I've been playing around with xml.Marshal() which takes an
http.ResponseWriter and some other stuff. The particular application
I'm dealing with requires me to set a Content-Length in the response
Header. I know that I can get the length of the marshall'd xml and set
the content-length in the header by hand, but after I logged the h.RW
I noticed that the body length is already in there. Is there a way I
can cause, force, enable that Content-Length to be set in a header?
Thanks!

Brad Fitzpatrick

unread,
Dec 19, 2011, 2:09:49 PM12/19/11
to yourcomputerpal, golang-nuts
Once you write to the ResponseWriter, the bytes start hitting the wire and the headers are sent, if they haven't been sent yet.

If you need to set a Content-Length, you need to write to your own buffer, set the header, and then send everything at once.

var buf bytes.Buffer
err := xml.Marshal(&buf, ...)
...
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
io.Copy(w, &buf)

Brandon Mercer

unread,
Dec 19, 2011, 3:39:54 PM12/19/11
to golang-nuts
Yup, that works. :) I was just wondering because I definitely see that
body length in there. Thanks!

Brad Fitzpatrick

unread,
Dec 19, 2011, 3:43:38 PM12/19/11
to Brandon Mercer, golang-nuts
It counts the body length to make sure you send exactly what you declare, but by the time your ServeHTTP method is done, it's too late to send headers.  That size can only be used as a sanity check to decide whether or not the connection is in a hosed state.  (if you send Content-Length: 100 but send 5 bytes, clients will be very confused, and we should shut down that TCP connection...)
Reply all
Reply to author
Forward
0 new messages