0

下面是我运行的代码问题是我找不到 404 页面而不是 graphql 游乐场页面是否可以使用带有 gqlgen 的 httprouter 或者我需要返回 chi 或 mux 我也无法使用中间件因为 r 没有 Use 方法

package main

import (
    "gographql-server/graph"
    "gographql-server/graph/generated"
    "log"
    "net/http"
    "os"

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

const defaultPort = "8080"

func PlaygroundHandler() httprouter.Handle {
    h := playground.Handler("GraphQL", "/query")

    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
        h.ServeHTTP(w, req)
    }
}

func GraphqlHandler() httprouter.Handle {
    h := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))

    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
        h.ServeHTTP(w, req)
    }
}

func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = defaultPort
    }
    r := httprouter.New()
    r.POST("/query", GraphqlHandler())
    r.GET("/", PlaygroundHandler())
    // r.Use(middleware.RequestID)
    // r.Use(middleware.Logger)
    // r.Use(middleware.Recoverer)
    // r.Use(middlewares.AuthMiddleware())
    log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
    log.Fatal(http.ListenAndServe(":"+port, nil))
}

4

1 回答 1

1

如果你在这一行传递nil给:http.ListenAndServe()

log.Fatal(http.ListenAndServe(":"+port, nil))

这意味着使用DefaultServeMuxnet/http包的。但是您没有在默认多路复用器中注册任何处理程序,您使用创建自己的路由器httprouter.New(),并在其中注册处理程序。

因此,您必须将此路由器传递给ListenAndServe()

log.Fatal(http.ListenAndServe(":"+port, r))
于 2021-08-09T11:03:04.760 回答