Go 的 net/http 在 1.22 引入了更方便的 pattern matching:「Routing Enhancements for Go 1.22」。
用官方的範例,現在可以處理路徑裡的參數了:
http.Handle("GET /posts/{id}", handlePost2)
後續可以透過 PathValue()
取出來:
idString := req.PathValue("id")
而優先順序則是依照吻合度定義:
The precedence rule is simple: the most specific pattern wins. This rule matches our intuition that
posts/latests
should be preferred toposts/{id}
, and/users/{u}/posts/latest
should be preferred to/users/{u}/posts/{id}
. It also makes sense for methods. For example,GET /posts/{id}
takes precedence over/posts/{id}
because the first only matches GET and HEAD requests, while the second matches requests with any method.
但是當有重疊卻無法判斷相對吻合度的 rule 被加進去時,會直接 panic()
:
What if two patterns overlap but neither is more specific? For example,
/posts/{id}
and/{resource}/latest
both match/posts/latest
. There is no obvious answer to which takes precedence, so we consider these patterns to conflict with each other. Registering both of them (in either order!) will panic.
這的確是種方法啦... 而且留有之後處理的空間,真的有好的方法就可以把 panic()
的邏輯改成新的共識。