I've been playing around with gorilla-websocket in Go, and as I implemented the basic echo example, I logged an error after deploying the server,
Origin is not found Websocket version != 13
I found a way to bypass this by making the function that checks the origin always return true
var wsUpgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
But it doesn't feel right. Therefore, I am looking for a way to fix that issue.
Update: After having another look at the issue it seems like I'm actually looking to add the origin header to the client implementation which is the javascript websocket implementation
@benjic Im connecting to the websocket via a javascript html5 application that isn't hosted on the same server but is run locally by me via chrome
So how do I do that.
Reading through the Gorilla WebSocket Documentation indicates that when a nil value is provided for the CheckOrigin
field of an Upgrader
type a safe default is used. The default checks the Origin field of the incoming request with the Host header value to confirm they are equal before allowing the request. The documentation indicates that browsers do not enforce cross origin validity and it is the responsibility of the server application to enforce. You can see exactly how this is done in the source code for the Gorilla library.
The documentation and source indicate an Upgrade
function in the websocket
package that acts as a factory for your example code above. The factory function takes a custom buffer size and overrides the CheckOrigin to always return true. Instead of creating a custom Upgrader
you can use this factory function in the HttpHandler
to upgrade your connections.
func webSocketHandler(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
defer conn.Close()
if err != nil {
http.Error(w, err, http.StatusInternalServerError)
return
}
conn.WriteMessage(websocket.TextMessage, []byte("Hello, world!"))
}