如何使用 gorilla mux 实现不区分大小写的 URL 匹配

How to implement case insensitive URL matching using gorilla mux

我需要在 gorilla mux 中实现不区分大小写的 URL 匹配 it is done here for built in mux

我尝试使用这样的中间件实现同样的效果

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
}

但如果 URL 大小写改变,它仍然会抛出 404,有没有办法使用 gorilla-mux

来实现它

不幸的是,在撰写本文时,在 URL 匹配 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.

我建议使用您提供的 link 中的示例。

例如

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)
    })
}

然后,只需包装您的多路复用器即可。

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

IMO 其实还不错。