我想创建一个ServeMux来匹配整个子树。
例如:
有一个处理程序能够处理所有与用户相关的功能。 列出所有可能的用户相关网址(如
)并不好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)
是否可以匹配以' / user'开头的所有网址?在一行?
答案 0 :(得分:3)
对于example,如果路径不存在,它会自动调用/user/
处理程序:
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/user/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "generic user handler: %v\n", req.URL.Path)
})
mux.HandleFunc("/user/f1/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "f1 generic handler, %v\n", req.URL.Path)
})
mux.HandleFunc("/user/f1/sf1", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "sf1 generic handler, %v\n", req.URL.Path)
})
fmt.Println(http.ListenAndServe(":9020", mux))
}
制作:
➜ 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