首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有可能让net.http.ServeMux匹配整个子树?

有没有可能让net.http.ServeMux匹配整个子树?
EN

Stack Overflow用户
提问于 2014-06-27 00:08:31
回答 1查看 1K关注 0票数 1

我想创建一个ServeMux来匹配整个子树。

例如:

有一个处理程序能够处理所有与用户相关的函数。列出所有可能的与用户相关的urls并不好,比如

代码语言:javascript
复制
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?

EN

回答 1

Stack Overflow用户

发布于 2014-06-27 00:21:08

对于example,如果路径不存在,它将自动调用/user/处理程序

代码语言:javascript
复制
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))
}

产生:

代码语言:javascript
复制
➜ 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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24435393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档