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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度