Gorilla Mux Regex

☆樱花仙子☆ 提交于 2021-02-19 03:28:12

问题


I'm using the Mux package from the Golang Gorilla Toolkit for my routes.

Consider the following routes:

m.HandleFunc("/admin/install", installHandler).Methods("GET")
m.HandleFunc("/admin/^((?!install).)*$", adminHandler).Methods("GET")
m.HandleFunc("/admin", adminHandler).Methods("GET")

The problem is with the regex of the middle route - it is not interpreted, so the route will not work!

m.HandleFunc("/admin/{^((?!install).)*$}", adminHandler).Methods("GET")

With the {} curly brackets doesn't work either. It is just ignored, and treated as /admin/

Neither does:

m.HandleFunc("/admin/{_dummy:^((?!install).)*$}", adminHandler).Methods("GET")

In short, what I'm trying to achieve here is to first match the /admin/install route, and that exact route I then want to exclude from the route below, using the regex, but it doesn't work.

Is there some way to use regex with the gorilla mux package?


回答1:


It is actually possible to do this:

m.HandleFunc(`/{_dummy:admin\/([^install]*).*}`, adminHandler).Methods("GET")

Edit:

As my answer to VonC's comment above, here a sample go app: https://play.golang.org/p/nYWNADK7Sr

Run it on your local pc. Try the following routes:

http://localhost:8080/admin/ - (returns "adminHandler")
http://localhost:8080/admin/something - (returns "adminHandler")
http://localhost:8080/admin/install - (returns "installHandler")

So yes VonC, it does solve the specific problem:

"to first match the /admin/install route, and that exact route I then want to exclude from the route below"

But it is correct that it doesn't mean "not followed by the word, install" - this is just an alternative approach which is possible within the bounds of the re2 syntax. To simply "ignore" or exclude the word install, if it happens to show up in the url.




回答2:


It doesn't work because golang regexp follows the re2 syntax, which doesn't support lookahead or lookbehind.

You might need to define an handler for /admin/install first.
Then all others /admin/xxx would be for other routes (ie not /admin/install)

Actually, the OP SK84 adds in the comments:

Even if admin/install is defined first, /admin/ will also be executed. That's what I wanted to avoid.

I guess I need to code around it inside the admin handler then - easy, but not as pretty as this would have been if it had worked.



来源:https://stackoverflow.com/questions/28950606/gorilla-mux-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!