99designs / gqlgen

go generate based graphql server library
https://gqlgen.com
MIT License
9.96k stars 1.17k forks source link

when i setup subscription endpoint(websocket connection) in my gqlgen + go code, it display an error as unable to upgrade *http.response to websocket websocket: request origin not allowed by Upgrader.CheckOrigin: #2826

Open melkamu-zinabu opened 1 year ago

melkamu-zinabu commented 1 year ago

when i try to start websocket connection from frontend code,it display an error as unable to upgrade *http.response to websocket websocket: request origin not allowed by Upgrader.CheckOrigin in the server side to fix it i update the package but it still persist

melkamu-zinabu commented 1 year ago

please help me

suryatresna commented 1 year ago

I've got the same issue. My problem was solved with the change using New instead of NewDefaultServer

something like this

srv := handler.New(graph.NewExecutableSchema(graph.Config{
Resolvers: resolver,
}))

If you use NewDefaultServer https://github.com/99designs/gqlgen/blob/master/graphql/handler/server.go#L35-L37, that can't override because WebSocket already initialize

aleksey-korolev commented 3 months ago

Origin header may be different or even missing depending on your frontend environment e.g. browser vs Postman client vs etc etc. You may have a look at default implementation of CheckOrigin to get better understanding how you'd like to customise this check: https://github.com/gorilla/websocket/blob/5e002381133d322c5f1305d171f3bdd07decf229/server.go#L87

andreimatei commented 2 months ago

Like @suryatresna said, I seem to not be able to use NewDefaultServer if I want to override the Upgrader. But I'm quite confused since a bunch of examples in the gqlgen code do use NewDefaultServer, and afterwards add the websocket transport with custom options. Are they all really broken? For example: https://gqlgen.com/recipes/cors/

ericmak624 commented 1 month ago

@andreimatei I think the examples are all broken. I was running into the same issue, and after digging into the code a bit I think I found the reason:

NewDefaultServer uses AddTransport internally to add a ws tranport. When users call AddTransport again in product code, it will use append to add another ws transport to the transports slice. So we end up with 2 ws transports.

In srv.ServeHTTP's getTransport(r), it uses the first transport from the transports slice so the one added by users is ignored. This explains why user defined ws Upgrader doesn't do anything since it's not being used.

For now, I can work around this by using New instead of NewDefaultServer and copy the rest from NewDefaultServer.