4

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?

4

2 回答 2

5

实际上可以这样做:

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

编辑:

作为我对 VonC 上述评论的回答,这里有一个示例 go 应用程序:https: //play.golang.org/p/nYWNADK7Sr

在本地电脑上运行它。尝试以下路线:

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

所以是的VonC,它确实解决了具体问题:

“首先匹配 /admin/install 路线,然后我想从下面的路线中排除那个确切的路线”

但正确的是,它并不意味着“后面没有安装这个词” ——这只是在 re2 语法范围内可能的另一种方法。简单地“忽略”或排除安装这个词,如果它恰好出现在 url 中。

于 2015-03-23T22:24:03.477 回答
1

它不起作用,因为 golang 正则表达式遵循re2 语法,它不支持前瞻或后瞻。

您可能需要为/admin/install first定义一个处理程序。
然后所有其他人/admin/xxx将用于其他路线(即不是/admin/install

实际上,OP SK84在评论中添加了:

即使先定义了 admin/install,也会执行 /admin/。这就是我想要避免的。

我想我需要在管理处理程序中围绕它进行编码 - 很容易,但如果它起作用的话,它就不会那么漂亮了。

于 2015-03-09T20:00:33.913 回答