英文:
How Can I handle any url beginning with some url in Go?
问题
你好,我正在使用Go语言中的gorilla/mux库,并且我想处理以"/a/b/c"开头的任何URL。
我尝试了以下代码:
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc(`/a/b/{_dummy:c(\/)?.*}`, Func1)
这样的URL可以是/a/b/c/d或/a/b/c/d/e。
英文:
Hi I am using gorilla/mux in go, and I want to handle any url that begins with : "/a/b/c"
I tried:
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc(`/a/b/{_dummy:c(\/)?.*}`, Func1)
that is the url can be /a/b/c/d or /a/b/c/d/e
答案1
得分: 4
根据gorilla/mux的文档:http://www.gorillatoolkit.org/pkg/mux#Route.PathPrefix
func (r *Router) PathPrefix(tpl string) *Route
PathPrefix使用URL路径前缀的匹配器注册一个新的路由。参见Route.PathPrefix()。
func (r *Route) PathPrefix(tpl string) *Route
PathPrefix为URL路径添加一个前缀匹配器。如果给定的模板是完整URL路径的前缀,则匹配成功。有关tpl参数的详细信息,请参见Route.Path()。
请注意,它不会特殊处理斜杠("/foobar/"将与前缀"/foo"匹配),因此您可能希望在此处使用尾部斜杠。
还请注意,Router.StrictSlash()的设置对具有PathPrefix匹配器的路由没有影响。
请注意,提供给PathPrefix()的路径表示一个“通配符”:调用PathPrefix("/static/").Handler(...)意味着处理程序将接收与"/static/*"匹配的任何请求。
所以你要找的是:
router := mux.NewRouter()
router.PathPrefix("/a/b/c/").HandleFunc(proxy.GrafanaHandler) // 匹配 /a/b/c/*
英文:
Per the documentation for gorilla/mux: http://www.gorillatoolkit.org/pkg/mux#Route.PathPrefix
func (r *Router) PathPrefix(tpl string) *Route
> PathPrefix registers a new route with a matcher for the URL path
> prefix. See Route.PathPrefix().
func (r *Route) PathPrefix(tpl string) *Route
> PathPrefix adds a matcher for the URL path prefix. This matches if the
> given template is a prefix of the full URL path. See Route.Path() for
> details on the tpl argument.
>
> Note that it does not treat slashes specially ("/foobar/" will be
> matched by the prefix "/foo") so you may want to use a trailing slash
> here.
>
> Also note that the setting of Router.StrictSlash() has no effect on
> routes with a PathPrefix matcher.
> Note that the path provided to PathPrefix() represents a "wildcard":
> calling PathPrefix("/static/").Handler(...) means that the handler
> will be passed any request that matches "/static/*".
So what you're looking for is:
router := mux.NewRouter()
router.PathPrefix("/a/b/c/").HandleFunc(proxy.GrafanaHandler) // matches /a/b/c/*
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论