github.com/99designs/gqlgen@v0.17.45/docs/content/recipes/cors.md (about) 1 --- 2 title: "Setting CORS headers using rs/cors for gqlgen" 3 description: Use the best of breed rs/cors library to set CORS headers when working with gqlgen 4 linkTitle: CORS 5 menu: { main: { parent: "recipes" } } 6 --- 7 8 Cross-Origin Resource Sharing (CORS) headers are required when your graphql server lives on a different domain to the one your client code is served. You can read more about CORS in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). 9 10 ## rs/cors 11 12 gqlgen doesn't include a CORS implementation, but it is built to work with all standard http middleware. Here we are going to use the fantastic `chi` and `rs/cors` to build our server. 13 14 ```go 15 package main 16 17 import ( 18 "net/http" 19 20 "github.com/99designs/gqlgen/graphql/handler/transport" 21 "github.com/99designs/gqlgen/_examples/starwars" 22 "github.com/99designs/gqlgen/graphql/handler" 23 "github.com/go-chi/chi" 24 "github.com/rs/cors" 25 "github.com/gorilla/websocket" 26 "github.com/99designs/gqlgen/graphql/playground" 27 ) 28 29 func main() { 30 router := chi.NewRouter() 31 32 // Add CORS middleware around every request 33 // See https://github.com/rs/cors for full option listing 34 router.Use(cors.New(cors.Options{ 35 AllowedOrigins: []string{"http://localhost:8080"}, 36 AllowCredentials: true, 37 Debug: true, 38 }).Handler) 39 40 41 srv := handler.NewDefaultServer(starwars.NewExecutableSchema(starwars.NewResolver())) 42 srv.AddTransport(&transport.Websocket{ 43 Upgrader: websocket.Upgrader{ 44 CheckOrigin: func(r *http.Request) bool { 45 // Check against your desired domains here 46 return r.Host == "example.org" 47 }, 48 ReadBufferSize: 1024, 49 WriteBufferSize: 1024, 50 }, 51 }) 52 53 router.Handle("/", playground.Handler("Starwars", "/query")) 54 router.Handle("/query", srv) 55 56 err := http.ListenAndServe(":8080", router) 57 if err != nil { 58 panic(err) 59 } 60 } 61 62 ```