gpt4 book ai didi

http - 将 http.NewServeMux 放入 http.NewServeMux

转载 作者:IT王子 更新时间:2023-10-29 02:26:12 26 4
gpt4 key购买 nike

这是我的代码。我想将 mux1 作为子路由器放入 mux.Handle 中。接下来,我运行代码。我可以访问路径/index 但我无法访问路径/index/sub1。不知道为什么我可以访问/index但不能访问/index/sub1?

package main

import (
"io"
"net/http"
)

func main() {
mux1 := http.NewServeMux()
mux1.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "sub index")
})
mux1.HandleFunc("/sub1", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "sub 1")
})

mux := http.NewServeMux()
mux.Handle("/index", mux1)

http.ListenAndServe(":8000", mux)
}

最佳答案

您的示例不起作用,因为您使用了 /index 路径来注册“外部”处理程序,这是一个单一的路径(因为它没有以斜线结尾 /) 而不是根子树(即所有以 /index/ 开头的路径)。这记录在 http.ServeMux :

Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.

而且因为“子路由器”不会看到您用来注册处理程序的路径,例如 "/""/sub1",但是 完整路径,即:"/index/""/index/sub1"

所以主路由器应该做的是“剥离”“/index” 前缀,这是它注册到的路径(没有尾部斜线)。幸运的是,标准库有一个现成的解决方案:http.StripPrefix() .

所以工作解决方案:

mux1 := http.NewServeMux()
mux1.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "sub index")
})
mux1.HandleFunc("/sub1", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "sub 1")
})

mux := http.NewServeMux()
mux.Handle("/index/", http.StripPrefix("/index", mux1))

http.ListenAndServe(":8000", mux)

测试它:

  • 网址:http://localhost:8000/index/
    响应:子索引

  • 网址:http://localhost:8000/index/sub1
    响应:sub 1

关于http - 将 http.NewServeMux 放入 http.NewServeMux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50528201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com