默认服务器 mux 如何匹配 url 模式

How does default server mux match url pattern

我看到使用以下代码从请求路径中提取 url 参数的简单路由器实现。

handler := http.NewServerMux()
handler.HandleFunc('/user/', func(w http.ResponseWriter, r *http.Request) {
     name := strings.Replace(r.URL.Path, '/user/', "", 1)// this code

    io.WriteString(w, fmt.Sprintf("Hello %s\n",name)
})

然后他们将是另一条路线,如 /user(注意缺少尾部斜杠)。

handler.HandleFunc('/user', handleUser)

比如说 r.URL.Path/user/name。第一条路线将匹配,而第二条较短的路径将不匹配。从技术上讲,请求路径不应匹配任何路由,因为一个路由太长而另一个路由太短。

这提出了一个问题,即 Golang mux 在将请求与路由匹配时遵循什么规则。乍一看似乎是在取最长的路径匹配,但如果最短路径在程序的源代码中最先定义呢?

谁能简单解释一下 ServerMux 的行为方式。

最好的解释是在 documentation for the http package 中找到的官方解释。部分:

Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.

Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".

一如既往,如果您需要更多详细信息,请阅读文档。