gpt4 book ai didi

go - 为什么这会在每个 URL 请求上得到服务?

转载 作者:IT王子 更新时间:2023-10-29 01:33:52 25 4
gpt4 key购买 nike

package main

import "fmt"
import "net/http"

func home(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "What!")
}

func bar(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Bar!")
}

func main() {
http.HandleFunc("/", home)
http.HandleFunc("/foo", bar)
http.ListenAndServe(":5678", nil)
}

如果我访问 /foobar 将运行。

如果我访问 //any/other/pathhome 将运行。

知道为什么会这样吗?我该如何处理 404?

最佳答案

这是一种设计行为 - 为以 / 结尾的路径定义的处理程序也将处理任何子路径。

Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".

http://golang.org/pkg/net/http/#ServeMux

您必须为 404 实现您自己的逻辑。考虑 golang 文档中的以下示例:

mux := http.NewServeMux()
mux.Handle("/api/", apiHandler{})
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "Welcome to the home page!")
})

http://golang.org/pkg/net/http/#ServeMux.Handle

关于go - 为什么这会在每个 URL 请求上得到服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25775213/

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