我最终编写了自己的自定义匹配函数,并使用了go的正则表达式包。这很容易做到,以下是一个示例:
import (
...
"net/http"
"net/url"
"regexp"
"github.com/gorilla/mux"
...
)
...
muxRouter := mux.NewRouter()
muxRouter.
Methods("GET", "POST").
Schemes("https").
MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
match, _ := regexp.MatchString("/users.*", r.URL.Path)
return match
}).
HandlerFunc(m.ServeHTTP)
关键是使用:
HandlerFunc(f func(http.ResponseWriter, *http.Request))
而不是:
HandleFunc(path string, f func(http.ResponseWriter, *http.Request))
。
HandlerFunc
必须在匹配器之后。这将允许你编写自己的自定义匹配函数。
性能
对于我的应用场景,这个表现良好,但如果你想要更好的性能,可以尝试使用预编译的 r, _ := regexp.Compile("p([a-z]+)ch")
。
你可能需要使用一个带有一个已经存储了预编译正则表达式模式的 f func(http.ResponseWriter, *http.Request)
结构体。
Go 正则表达式示例:
https://gobyexample.com/regular-expressions
开始吧!希望你们会发现这篇文章有帮助。