gographqlgqlgenhttprouter

404 page not found when trying to use Gqlgen with julienschmidt/httprouter


Below is the code I run the issue is that I get 404 page not found instead of the graphql playground page Is it possible to work with httprouter with gqlgen or do I need to go back to chi or mux I also was not able to use middlewares because r does not have Use method

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


Solution

  • If you pass nil to http.ListenAndServe() in this line:

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

    That means the DefaultServeMux of the net/http package is used. But you you don't register any handlers in the default mux, you create your own router using httprouter.New(), and you register handlers in that.

    So you must pass this router to ListenAndServe():

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