使用 gqlgen 为 GraphQL 添加带有 go-chi 路由器的身份验证中间件

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

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))
}

按此使用 handler.NewDefaultServer(...)

参考资料 https://gqlgen.com/recipes/authentication/

log.Fatal(http.ListenAndServe(":8080", nil)) 应该 log.Fatal(http.ListenAndServe(":8080", router))

看起来 port var 未设置。