1

I'm trying to add CORS to my gqlgen server using the code from the official docs, but when I try to connect to the server from http://localhost:3000 the connection is refused.

package main

import (
    "log"
    "net/http"
    "os"

    "github.com/99designs/gqlgen/graphql/handler"
    "github.com/99designs/gqlgen/graphql/handler/transport"
    "github.com/99designs/gqlgen/graphql/playground"
    "github.com/go-chi/chi"
    "github.com/gorilla/websocket"
    "github.com/megajon/gqlgen-cors/graph"
    "github.com/rs/cors"
)

const defaultPort = "8081"

func main() {
    port := os.Getenv("PORT")
    if port == "" {`your text`
        port = defaultPort
    }

    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:3000"},
        AllowCredentials: true,
        Debug:            true,
    }).Handler)

    srv := handler.NewDefaultServer(graph.NewExecutableSchema(graph.Config{Resolvers: &graph.Resolver{}}))
    srv.AddTransport(&transport.Websocket{
        Upgrader: websocket.Upgrader{
            CheckOrigin: func(r *http.Request) bool {
                // Check against your desired domains here
                return r.Host == "example.org"
            },
            ReadBufferSize:  1024,
            WriteBufferSize: 1024,
        },
    })

    router.Handle("/", playground.Handler("GraphQL playground", "/query"))
    router.Handle("/query", srv)

    log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
    err := http.ListenAndServe(":"+port, router)
    if err != nil {
        panic(err)
    }
}
dave
  • 62,300
  • 5
  • 72
  • 93
megajon
  • 37
  • 2

1 Answers1

1

It turns out the issue wasn't CORS, but the fact that the gqlgen API was running from a Windows Powershell and the front end app was running from a wsl ubuntu terminal. Which is essentially two separate networks. Once I ran both apps in the same environment the problem was resolved.

megajon
  • 37
  • 2