2

当我尝试使用 GraphQL 设置 Go Web 服务器时,我将用作模板。它基本上是杜松子酒99designs/gqlgen.

当我基于 net/http 包创建一个基本的 gqlgen 服务器时,GraphQL 订阅的声明按预期工作。

package main

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

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

const defaultPort = "8080"

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

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

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

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

但是当我添加杜松子酒时,像这样:

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/jawil003/gqlgen-todos/graph"
    "github.com/jawil003/gqlgen-todos/graph/generated"

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

// Defining the Graphql handler
func graphqlHandler() gin.HandlerFunc {
    // NewExecutableSchema and Config are in the generated.go file
    // Resolver is in the resolver.go file
    h := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))

    return func(c *gin.Context) {
        h.ServeHTTP(c.Writer, c.Request)
    }
}

// Defining the Playground handler
func playgroundHandler() gin.HandlerFunc {
    h := playground.Handler("GraphQL", "/query")

    return func(c *gin.Context) {
        h.ServeHTTP(c.Writer, c.Request)
    }
}

func main() {
    // Setting up Gin
    r := gin.Default()
    r.POST("/query", graphqlHandler())
    r.GET("/", playgroundHandler())
    r.Run()
}

我得到这个问题:

{ "error": "无法连接到 websocket 端点 ws://localhost:8080/query。请检查端点 url 是否正确。" }

是否有任何已知的解决方案可以使 gin 与 graphql 订阅一起使用?

4

1 回答 1

0

您好,修复Could not connect to websocket endpoint..Gin 更改r.POST("/query", graphqlHandler())为的错误r.Any("/query", graphqlHandler())

于 2021-10-23T14:02:48.553 回答