Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use this custom middleware #335

Open
ghost opened this issue Aug 9, 2021 · 1 comment
Open

How to use this custom middleware #335

ghost opened this issue Aug 9, 2021 · 1 comment

Comments

@ghost
Copy link

ghost commented Aug 9, 2021

I have this Custom authenitifcation middleware

package middlewares

import (
	"context"
	"net/http"

	"gographql-server/constants"
	"gographql-server/models"
)

// AuthMiddleware ...
func AuthMiddleware() func(handler http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {

			// populating ctx with req and res
			newCtx := context.WithValue(req.Context(), constants.KContext, models.MyCtx{Request: req, ResponseWriter: res})

			next.ServeHTTP(res, req.WithContext(newCtx))
		})
	}
}

When I try integrating it inside the main function I get r.Middleware undefined (type *httprouter.Router has no field or method Middleware)compilerMissingFieldOrMethod

package main

import (
	"gographql-server/graph"
	"gographql-server/graph/generated"
	"gographql-server/middlewares"
	"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.Middleware(middlewares.AuthMiddleware())
	log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
	log.Fatal(http.ListenAndServe(":"+port, r))
}

@sreeram77
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant