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\n",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.
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.