duan0427 2019-03-18 05:06
浏览 20
已采纳

默认服务器多路复用器如何匹配网址格式

I have seen simple router implementation using the following code to extract url parameters from the request path.

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
",name)
})

Then they will be another route like /user (notice lacking trailing slash).

handler.HandleFunc('/user', handleUser)

Lets say for example r.URL.Path is /user/name. The first route will match while there will be no match for second shorter path. Technically, the request path should not match any route as one is too long for a match and other one too short.

This raises a question of what rules Golang mux follow when matching request to routes. It appears at first thought that it is taking the longest match of the path but what if the shortest path is defined first in the source of the program?

Can someone please give a simple explanation on how the ServerMux behaves.

  • 写回答

1条回答 默认 最新

  • duangan9251 2019-03-18 07:12
    关注

    The best explanation is the official one, found in the documentation for the http package. In part:

    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 == "/".

    As always, if you need more details, read the docs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM