volatiletech / authboss

The boss of http auth.
MIT License
3.79k stars 204 forks source link

Middleware chaining for authboss route #330

Open yusufmalikul opened 2 years ago

yusufmalikul commented 2 years ago

I have this part on my code:

pub.HandleFunc("/version", logHandler(version))

func logHandler(next http.HandlerFunc) http.HandlerFunc {
    // logger
}

func version(w http.ResponseWriter, r *http.Request) {
    // print version
}

How to call logHandler for authboss route? I take this from authboss-sample but don't know where to apply the middleware chaining:

mux.Mount("/auth", http.StripPrefix("/auth", ab.Config.Core.Router))

or it's not possible without modifying the authboss codebase?

stephenafamo commented 2 years ago

Try this:

First, change logHandler to this:

func logHandler(next http.handler) http.Handler {
    // logger
}

It is generally better to use http.Handler for middlewares instead of http.HandlerFunc. Handler is an interface which any router satisfies and helps to chain middlewares better.

Then you can wrap the authboss handler like this:

mux.Mount("/auth", http.StripPrefix("/auth", logHandler(ab.Config.Core.Router)))