让我们以以下模式为例:
package main
import (
"fmt"
"net/http"
)
func main() {
admin := http.NewServeMux()
admin.HandleFunc("/", root)
admin.HandleFunc("/foo", foo)
http.Handle("/admin", admin)
http.ListenAndServe(":4567", nil)
}
func root(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Admin: ROOT")
}
func foo(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Admin: FOO")
}为什么当我运行/admin时,它会触发根处理程序,而当我运行/admin/foo时,它却不会?需要说明的是,我并不是在寻找替代包,我实际上有一个自定义路由器,我只是对这里发生的事情很好奇,因为这个模式对我来说没有多大意义。
发布于 2014-09-16 02:07:35
就像@DewyBroto所说的,你必须使用子多路复用中的完整路径。
你可以像这样做一个包装器:
func NewChildMux(prefix string, vars ...interface{}) *http.ServeMux {
sm := http.NewServeMux()
for i := 0; i < len(vars); i += 2 {
path := prefix + vars[i].(string)
sm.HandleFunc(path, vars[i+1].(func(http.ResponseWriter, *http.Request)))
}
return sm
}
func main() {
admin := NewChildMux("/admin",
"/", root,
"/foo/", foo,
)
http.Handle("/admin/", admin)
http.ListenAndServe(":4567", nil)
}发布于 2014-09-16 02:34:48
尝试以下操作:
func main() {
admin := http.NewServeMux()
// Prefix all paths with the mount point. A ServeMux matches
// the full path, even when invoked from another ServeMux.
mountPoint := "/admin"
admin.HandleFunc(mountPoint, root)
admin.HandleFunc(mountPoint + "/foo", foo)
// Add a trailing "/" to the mount point to indicate a subtree match.
http.Handle(mountPoint + "/", admin)
http.ListenAndServe(":4567", nil)
}https://stackoverflow.com/questions/25853257
复制相似问题