go - 如何使用 Gorilla Mux 进行 URL 匹配?

标签 go routes mux

我有一个验证器函数来检查给定路径是否与路径数组中的路径匹配。

当前逻辑:

var allowed := String{"/users", "/teams"}
func Validator(path String) bool {
   for _, p := range allowed {
     if path == p {
        return true
     }
   }
   return false
}

我想使用 golang gorilla mux 替换它,因为我可能有路径变量。 mux 的 github 存储库显示“HTTP 路由器和 URL 匹配器”。但是,没有关于如何使用它进行 URL 匹配的示例。

最佳答案

这是我通过代码解决这个问题的方法:

// STEP 1: create a router
router := mux.NewRouter()

// STEP 2: register routes that are allowed
router.NewRoute().Path("/users/{id}").Methods("GET")
router.NewRoute().Path("/users").Methods("GET")
router.NewRoute().Path("/teams").Methods("GET")

routeMatch := mux.RouteMatch{}

// STEP 3: create a http.Request to use in Mux Route Matcher
url := url.URL { Path: "/users/1" }
request := http.Request{ Method:"GET", URL: &url }

// STEP 4: Mux's Router returns true/false
x := router.Match(&request, &routeMatch)
fmt.Println(x) // true

url = url.URL { Path: "/other-endpoint" }
request = http.Request{ Method:"GET", URL: &url }

x = router.Match(&request, &routeMatch)
fmt.Println(x) // false

关于go - 如何使用 Gorilla Mux 进行 URL 匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60613319/

相关文章:

go - 如何使用 gorilla mux 对所有路由应用相同的处理程序

转到 channel ,tcp/ip 端口映射不返回所有打开的端口

go - 在选择中的同一 channel 上读写

javascript - 在 Chrome 中选择 "Open Link in New Tab"选项时,应用程序路由重定向到 Angular 应用程序中的登录

go - 更改引用标志的 if 语句中的变量值

go - gorilla Mux相同端点多个查询参数

go - slice 中的长度和容量方法

sockets - 在不关闭连接的情况下关闭从 TCP 连接读取的 goroutine

ruby-on-rails - Ruby on Rails 中的单数命名路线

AngularJS:root 时路由提供程序不起作用