Adding authentication middleware with go-chi router for GraphQL with gqlgen

2.2k views Asked by At
package main

import (
    "github.com/go-chi/chi"
    "go-graphql-demo/graph"
    "go-graphql-demo/graph/generated"
    "log"
    "net/http"
    "os"

    "github.com/99designs/gqlgen/graphql/handler"
    "github.com/99designs/gqlgen/graphql/playground"
)



func main() {

    router := chi.NewRouter()

    srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))

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

    log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Using handler.NewDefaultServer(...) as per this Cannot connect to graphql playground when using go-chi router

References https://gqlgen.com/recipes/authentication/

1

There are 1 answers

0
Curtis Menmuir On BEST ANSWER

log.Fatal(http.ListenAndServe(":8080", nil)) should be log.Fatal(http.ListenAndServe(":8080", router))

Also looks like port var is not set.