Subrouters and middlewares

112 views
Skip to first unread message

fasmat

unread,
Apr 28, 2021, 7:14:48 AM4/28/21
to Gorilla web toolkit
Hi everyone,

I have a situation where I want to add middlewares to all routes except some that start with a specific pattern. This is the code I'm currently using:

r := mux.NewRouter()
r.Use(MW1)
r.Use(MW2)

r.Handle(...)
// some more handlers ...
r.Handle(...)

sub := r.PathPrefix("/static").Subrouter()
sub.Use(MW3)
sub.PathPrefix("/").Handler(http.FileServer(...)) // serve from filesystem on this route

I want to have MW3 only executed on the static route, which works perfectly fine. MW1 and MW2 should be execute everywhere BUT on the static route. Is there any way to easily achieve this?

Thanks for any help in advance

rol...@gmail.com

unread,
Apr 28, 2021, 7:47:19 AM4/28/21
to Gorilla web toolkit
Hello,

you could write a function e.g. addHandler(r, routeToAdd) and apply different r.Use(...) and r.Handle(...) calls based of  string matching:

match, _ := regexp.MatchString("/static", "/static")
if match {
   
} else {
   // non-static
}

This function would be then called for all route strings.

BR,
Roland

fasmat

unread,
Apr 28, 2021, 8:32:48 AM4/28/21
to Gorilla web toolkit
Hi Roland,

thanks for your suggestion! We tried this approach but want to move the subrouter configuration to it's own package (we want to share it between multiple applications) and avoid having "/static" defined in multiple places. So we tried the following:

r := mux.NewRouter()
// globally used middlewares (e.g. logging)
r.Use(GlobalMW)

sub1 := r.PathPrefix("/").Subrouter()
sub1.Use(MW1)
sub1.Use(MW2)
sub1.Handle(...)
sub1.Handle(...)

sub2 := r.PathPrefix("/static").Subrouter()
sub2.Use(MW3)
sub2.PathPrefix("/").Handler(http.FileServer(...)) // serve from filesystem on this route

This seems to work for us for now.

Thanks,
fasmat
Reply all
Reply to author
Forward
0 new messages