git.sr.ht/~sircmpwn/gqlgen@v0.0.0-20200522192042-c84d29a1c940/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  	"git.sr.ht/~sircmpwn/gqlgen/graphql/handler/transport"
    21      "git.sr.ht/~sircmpwn/gqlgen/example/starwars"
    22  	"git.sr.ht/~sircmpwn/gqlgen/graphql/handler"
    23  	"github.com/go-chi/chi"
    24  	"github.com/rs/cors"
    25  )
    26  
    27  func main() {
    28  	router := chi.NewRouter()
    29  
    30  	// Add CORS middleware around every request
    31  	// See https://github.com/rs/cors for full option listing
    32  	router.Use(cors.New(cors.Options{
    33  		AllowedOrigins:   []string{"http://localhost:8080"},
    34  		AllowCredentials: true,
    35  		Debug:            true,
    36  	}).Handler)
    37  
    38  
    39      srv := handler.New(starwars.NewExecutableSchema(starwars.NewResolver()))
    40      srv.AddTransport(&transport.Websocket{
    41          Upgrader: websocket.Upgrader{
    42              CheckOrigin: func(r *http.Request) bool {
    43                  // Check against your desired domains here
    44                   return r.Host == "example.org"
    45              },
    46              ReadBufferSize:  1024,
    47              WriteBufferSize: 1024,
    48          },
    49      })
    50  
    51  	router.Handle("/", handler.Playground("Starwars", "/query"))
    52  	router.Handle("/query", srv)
    53  
    54  	err := http.ListenAndServe(":8080", router)
    55  	if err != nil {
    56  		panic(err)
    57  	}
    58  }
    59  
    60  ```