CORS

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.

rs/cors

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.

packagemainimport("net/http""github.com/99designs/gqlgen/example/starwars""github.com/99designs/gqlgen/handler""github.com/go-chi/chi""github.com/rs/cors")funcmain(){router:=chi.NewRouter()// Add CORS middleware around every request
// See https://github.com/rs/cors for full option listing
router.Use(cors.New(cors.Options{AllowedOrigins:[]string{"http://localhost:8080"},AllowCredentials:true,Debug:true,}).Handler)router.Handle("/",handler.Playground("Starwars","/query"))router.Handle("/query",handler.GraphQL(starwars.NewExecutableSchema(starwars.NewResolver())),)err:=http.ListenAndServe(":8080",router)iferr!=nil{panic(err)}}