Writing response (setting cookie) from websocket connection

1,365 views
Skip to first unread message

Arpon Raksit

unread,
Jul 13, 2014, 10:44:37 AM7/13/14
to golan...@googlegroups.com
I'm writing a web app where the client and server communicate via a websocket. After a login event I set a cookie using the gorilla/sessions package, but in order for the browser to learn about this, I need to write a response from my socket handler. But since I've upgraded to a websocket connection, when I try to write anything to the http.ResponseWriter, I get an error "http: response.Write on hijacked connection".

Is there any way to write a response or set a cookie from a websocket handler? This would occur only when the socket closes.

Jesse McNelis

unread,
Jul 14, 2014, 12:00:50 AM7/14/14
to Arpon Raksit, golang-nuts
The websocket server struct has a Config field.
http://godoc.org/code.google.com/p/go.net/websocket#Server

The config type has a Header field.
http://godoc.org/code.google.com/p/go.net/websocket#Config

So you can make a http.Handler that creates a Server, sets it's
Config.Header to include your cookies and then call the server's
ServeHTTP() to continue with the websocket connection.

Arpon Raksit

unread,
Jul 14, 2014, 4:47:59 PM7/14/14
to golan...@googlegroups.com, arpon....@gmail.com, jes...@jessta.id.au
But the doc says that the Config.Header is sent at the opening handshake (this is also what the Header argument in http://www.gorillatoolkit.org/pkg/websocket#Upgrader.Upgrade seems to do). My situation is that the cookie is set after the connection has been opened, and I'd like to write it to the response when the connection closes. Sorry if I'm misunderstanding things.

Frits van Bommel

unread,
Jul 14, 2014, 5:33:24 PM7/14/14
to golan...@googlegroups.com, arpon....@gmail.com, jes...@jessta.id.au
Maybe you could just send the cookie as data over the websocket connection, and have the client set the cookie from javascript?

jasdel

unread,
Jul 14, 2014, 5:36:13 PM7/14/14
to golan...@googlegroups.com, arpon....@gmail.com, jes...@jessta.id.au
A cookie can only be written in the header of a response. Since the header is written during the upgrade it can no longer be re-written after the upgrade.  Alternatively if you control both endpoints you could send the cookie's value via the websock, which the other endpoint would read.


Cheers,

Arpon Raksit

unread,
Jul 15, 2014, 3:04:10 PM7/15/14
to golan...@googlegroups.com, arpon....@gmail.com, jes...@jessta.id.au
thanks! setting the cookie from the client is a perfectly acceptable solution for me.
Reply all
Reply to author
Forward
0 new messages