Last active
August 29, 2015 14:13
-
-
Save acoyfellow/72cfc18acb2f0eee0b96 to your computer and use it in GitHub Desktop.
Failing Go + Socket.io CORS server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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{}) | |
} |
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
I am able to see "on connect" and "on disconnect" console log messages in the Go server, but in the client:
(sometimes 2 or 3 of these per one error above)