I would like to create a ServeMux to match a whole subtree.
For example:
There is a handler is able to process all user-related functions. It's not nice to list all possible user-related urls like
mux := http.NewServeMux()
mux.Handle("/user/", TestHandler)
mux.Handle("/user/function01", TestHandler)
mux.Handle("/user/function02", TestHandler)
mux.Handle("/user/function03/sub-function01", TestHandler)
...
...
mux.Handle("/user/function100/sub-function01", TestHandler)
mux.Handle("/user/function100/sub-function01/sub-sub-function01", TestHandler)
Is it possible to match all urls which starts with '/user' in a single line ?
It will automaticly call the /user/
handler if the path doesn't exist, for example:
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/user/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "generic user handler: %v
", req.URL.Path)
})
mux.HandleFunc("/user/f1/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "f1 generic handler, %v
", req.URL.Path)
})
mux.HandleFunc("/user/f1/sf1", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "sf1 generic handler, %v
", req.URL.Path)
})
fmt.Println(http.ListenAndServe(":9020", mux))
}
Produces:
➜ curl localhost:9020/user/
generic user handler: /user/
➜ curl localhost:9020/user/f1/
f1 generic handler, /user/f1/
➜ curl localhost:9020/user/f1/sf1
sf1 generic handler, /user/f1/sf1
➜ curl localhost:9020/user/f2
generic user handler: /user/f2
➜ curl localhost:9020/user/f1/sf2
f1 generic handler, /user/f1/sf2