简体   繁体   中英

How to implement case insensitive URL matching using gorilla mux

I need to implement case insensitive URL matching in gorilla mux as it is done here for built in mux

I tried to achieve the same using middle-ware like this

router := mux.NewRouter()
router.Use(srv.GetCaseMiddleware())

//GetCaseMiddleware middleware to make match URL case insensitive
func (srv *Server) GetCaseMiddleware() (w mux.MiddlewareFunc) {
    var middleware mux.MiddlewareFunc = func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            r.URL.Path = strings.ToLower(r.URL.Path)
            next.ServeHTTP(w, r)
        })
    }
    return middleware
}

but still it throws 404 if URL case is changed,is there any way to implement it using gorilla-mux

Unfortunately, as of this writing, middleware functions are invoked after URL matching in gorilla/mux .

Mux supports the addition of middlewares to a Router, which are executed in the order they are added if a match is found, including its subrouters.

I would suggest going with the example in the link you provided.

eg

func CaselessMatcher(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        r.URL.Path = strings.ToLower(r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

Then, just wrap your multiplexer.

r := mux.NewRouter()
//...
handler := CaselessMatcher(r)

It's actually not bad IMO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM