Skip to content
New issue

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

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

Already on GitHub? # to your account

Disable middleware for some api #360

Closed
abbasnaqdi opened this issue Mar 23, 2018 · 4 comments
Closed

Disable middleware for some api #360

abbasnaqdi opened this issue Mar 23, 2018 · 4 comments

Comments

@abbasnaqdi
Copy link

Hi, I need to deactivate middleware in some api.

For example, I need to disable the auth user registry and use auth for other operations after the registry.

But in mux using r.Use (), all routers require auth operations.
How can I fix this problem ?

@elithrar
Copy link
Contributor

https://godoc.org/github.com/gorilla/mux#Router.PathPrefix

  • You can use r.PathPrefix(“/prefix”).Subrouter() to create a subrouter that only has specific middleware applied.

  • Alternatively, your middleware can take a list of paths to skip.

@bminer
Copy link

bminer commented Feb 7, 2019

Might be good to note this in the docs. It is not entirely clear that r.PathPrefix bypasses the middleware set in r.Use. Thoughts?

@bminer
Copy link

bminer commented Feb 11, 2019

Perhaps this behavior was changed after #431?

@vituchon
Copy link

Hi @bminer, allow me to share an approach to tackle a quite similar scenario...

scenario
assuming i got one endpoint for login purposes "/api/v1/user-login" (there is no sense to apply a a validation check)
and several endpoints for authenticated operations that requires to check if the client is validated, all of them with the following prefix "/api/v1/", for example "/api/v1/users" (to list all the users)

solution

func main() {
	r := mux.NewRouter()
	r.Path("/api/v1/user-login").Handler(http.HandlerFunc(UserLoginHandler))   // /api/v1/user-login will be NOT intercepted by ValidationMiddleWare
	api := r.PathPrefix("/api/v1").Subrouter()
	api.Use(ValidationMiddleware)
	api.Path("/users").Handler(http.HandlerFunc(UsersHandler)) // api/v1/users will be intercepted by ValidationMiddleWare
	
        ...

The trick is to define the fully qualified path "/api/v1/user-login" in the base route r, and then use the api subrouter for register the endspoints that requires a validation check.

Well, this work OK for me and hope it helps!
Also if there is some flaw or code smell, please notify me! i would be thankful!

Greetings
Víctor

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

No branches or pull requests

4 participants