Skip to content

Instantly share code, notes, and snippets.

@acoyfellow
Last active August 29, 2015 14:13
Show Gist options
  • Save acoyfellow/72cfc18acb2f0eee0b96 to your computer and use it in GitHub Desktop.
Save acoyfellow/72cfc18acb2f0eee0b96 to your computer and use it in GitHub Desktop.
Failing Go + Socket.io CORS server
package main
import (
"log"
"net/http"
"github.com/googollee/go-socket.io"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
type CrossOriginServer struct {}
func (s *CrossOriginServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
allowHeaders := "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"
if origin := req.Header.Get("Origin"); origin != "" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Credentials", "true") // Without this, error: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials.
rw.Header().Set("Access-Control-Allow-Methods", "POST, PUT, PATCH, GET, DELETE")
rw.Header().Set("Access-Control-Allow-Headers", allowHeaders)
}
if req.Method == "OPTIONS" {
return
}
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.On("connection", func(so socketio.Socket) {
log.Println("on connection")
so.On("disconnection", func() {
log.Println("on disconnect")
})
})
server.On("error", func(so socketio.Socket, err error) {
log.Println("error:", err)
})
mux := http.NewServeMux()
mux.Handle("/socket.io/", server)
mux.HandleFunc("/", SayHelloWorld)
mux.ServeHTTP(rw, req)
}
func main() {
log.Println("listening on :8080")
http.ListenAndServe(":8080", &CrossOriginServer{})
}
@acoyfellow
Copy link
Author

I am able to see "on connect" and "on disconnect" console log messages in the Go server, but in the client:

WebSocket connection to 'wss://api.domain.com/socket.io/?EIO=3&transport=websocket&sid=Pp_I3GaGUDpS9TBCeAVj' failed: Error during WebSocket handshake: Unexpected response code: 400 

api.domain.com/socket.io/?EIO=3&transport=polling&t=1420716581398-1473&sid=Pp_I3GaGUDpS9TBCeAVj:1 POST https://api.optkit.com/socket.io/?EIO=3&transport=polling&t=1420716581398-1473&sid=Pp_I3GaGUDpS9TBCeAVj 400 (Bad Request) 

(sometimes 2 or 3 of these per one error above)

@acoyfellow
Copy link
Author

Headers:

HTTP/1.1 400 Bad Request
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, PUT, PATCH, GET, DELETE
Access-Control-Allow-Origin: http://fiddle.jshell.net
Content-Type: text/plain; charset=utf-8
Date: Thu, 08 Jan 2015 11:44:36 GMT
Content-Length: 12
Connection: close

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment