http.ServeMux路由安装?

时间:2014-09-15 17:10:08

标签: go

让我们采取以下模式:

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时,它会赢?为了清楚起见,我不是在寻找替代方案,我实际上有一个自定义路由器,我只是对这里发生的事情感到好奇,因为这种模式不能制作对我来说很有道理。

2 个答案:

答案 0 :(得分:1)

像@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)
}

答案 1 :(得分:0)

尝试以下方法:

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)
}