golang中的路由的graphql问题

z5btuh9x  于 2023-06-19  发布在  Go
关注(0)|答案(1)|浏览(125)

我在代码中使用router作为:

router := chi.NewRouter()

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

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

得到的错误如下:

{
  "errors": {
    "message": "Unexpected token p in JSON at position 4",
    "stack": "SyntaxError: Unexpected token p in JSON at position 4"
  }
}

但当我尝试使用它与http.Handle它不显示错误,但代码内auth.middleware不运行。

gopyfrb3

gopyfrb31#

你可以试试这样:=

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

router := mux.NewRouter()

apiRouter := router.PathPrefix("/api").Subrouter()

apiRouter.Use(middleware.AuthMiddleware)

apiRouter.Handle("/graphql", gqlHandler)
router.Handle("/", playground.Handler("GraphQL playground", "/api/graphql"))

router.HandleFunc("/login", graph.LoginHandler)

corsHandler := cors.Default().Handler(router)

server := &http.Server{
    Addr:    ":" + port,
    Handler: corsHandler,
}

log.Printf("Connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(server.ListenAndServe())

相关问题