Graphql订阅不适用于Gin



当我尝试使用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订阅一起工作吗?

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

相关内容

最新更新