首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >http.ServeMux路由挂载?

http.ServeMux路由挂载?
EN

Stack Overflow用户
提问于 2014-09-16 01:10:08
回答 2查看 1K关注 0票数 2

让我们以以下模式为例:

代码语言:javascript
复制
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时,它却不会?需要说明的是,我并不是在寻找替代包,我实际上有一个自定义路由器,我只是对这里发生的事情很好奇,因为这个模式对我来说没有多大意义。

EN

回答 2

Stack Overflow用户

发布于 2014-09-16 02:07:35

就像@DewyBroto所说的,你必须使用子多路复用中的完整路径。

你可以像这样做一个包装器:

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

Stack Overflow用户

发布于 2014-09-16 02:34:48

尝试以下操作:

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

https://stackoverflow.com/questions/25853257

复制
相关文章

相似问题

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