golang多路复用器,路由通配符&自定义功能匹配 [英] golang mux, routing wildcard & custom func match

查看:148
本文介绍了golang多路复用器,路由通配符&自定义功能匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 mux 软件包,该软件包似乎工作得很好,除了它没有效果.似乎不支持复杂的路线,或者至少我不知道它是如何做到的.我有以下几种路线:

I'm using the mux package which seems to work quite well except that it doesn't seem to support complex routes or at least I don't get it how it does. I have several routes as following:

router := mux.NewRouter()
router.HandleFunc("/{productid}/{code}", product)
router.HandleFunc("/{user}", userHome)
router.HandleFunc("/search/price", searchPage)

所以我有两个问题:

  • 如何定义通配符路由(例如/search/price/*),以使诸如/search/price/29923/rage/200/color = red的请求能够匹配它?

  • How can I define a wildcard route such /search/price/* so that a request such /search/price/29923/rage/200/color=red can match it ?

是否可以向现有路线添加自定义条件?例如如果路由为/{productid}/{code} 并且函数x返回 true ,则使用此 handlerTrue ,如果它返回 false使用 handlerFalse .

Is it possible to add custom conditions to an existing route ? e.g. if the route is /{productid}/{code} and function x returns true , use this handlerTrue, if it returns false use handlerFalse.

我试图在路由中添加类似 .MatcherFunc(myfunction(ip)bool)的内容,但它抱怨路由器没有这种方法.

I've tried to add something like .MatcherFunc(myfunction(ip)bool) to the route but it complains that the router has no such method.

当前,我正在处理处理程序中的自定义"条件.

Currently I'm handling the 'custom' conditions inside the handler.

推荐答案

您可以使用正则表达式.像

You can use regexps. Something like

router.HandleFunc(`/search/price/{rest:[a-zA-Z0-9=\-\/]+}`, searchPage)

这样, rest 会捕获所有内容,因此在您的示例中, rest 将是 29923/rage/200/color = red .您将需要在代码中对其进行解析.

That way, rest will just capture everything, so in your example rest would be 29923/rage/200/color=red. You will need to parse that in your code.

不过,您可能想要一些类似的可选参数.

You probably want some like optional arguments, though.

router.HandleFunc(`/search{price:(\/price\/[0-9]+)?}{rage:(\/rage\/[0-9]+)?}{color:(\/color=[a-z]+)?}`, searchPage)

此后,您将获得vars price ="/price/29923" rage ="/rage/200" color ="/color =红色" ,您仍然需要对其进行解析,但是它更容易实现,并且您可以控制哪些参数是有效的.如果您跳过某些参数,它会按预期工作,例如./search/price/29923/color = red 只会给出一个空的 rage 变量,但仍然匹配.

After that, you get vars price = "/price/29923", rage = "/rage/200" and color = "/color=red", that you still need to parse, but its easier, and you get to control which parameters are valid. It works as expected if you skip some parameter, eg. /search/price/29923/color=red will just give an empty rage variable, but still match.

我不太明白你的第二个问题.

I don't quite get your second question.

这篇关于golang多路复用器,路由通配符&自定义功能匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆