我想创建一个ServeMux来匹配整个子树。
例如:
有一个处理程序能够处理所有与用户相关的函数。列出所有可能的与用户相关的urls并不好,比如
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”开头的urls?
发布于 2014-06-27 00:21:08
对于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/sf2https://stackoverflow.com/questions/24435393
复制相似问题