net/http
在 API
中创建一些端点。
我有一个
index
函数映射到 /
路径。我需要任何未明确声明为 path
的 mux
来返回 404
。
文档说:
请注意,由于以斜杠结尾的模式命名为根子树,因此模式“/”匹配与其他已注册模式不匹配的所有路径,而不仅仅是 Path ==“/”的 URL。
那么,我该怎么做呢?
遵循MRE:
package main
import (
"fmt"
"log"
"net/http"
)
func index(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "index")
}
func foo(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "foo")
}
func bar(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "bar")
}
func main() {
mux := http.NewServeMux()
s := &http.Server{
Addr: ":8000",
Handler: mux,
}
mux.HandleFunc("/", index)
mux.HandleFunc("/foo", foo)
mux.HandleFunc("/bar", bar)
log.Fatal(s.ListenAndServe())
}
当我跑步时:
$ curl 'http://localhost:8000/'
index
$ curl 'http://localhost:8000/foo'
foo
$ curl 'http://localhost:8000/bar'
bar
$ curl 'http://localhost:8000/notfoo'
index // Expected 404 page not found
由于您使用的多路复用器会将
/
处理程序与任何未注册的处理程序相匹配,因此您必须在调用 /
路径的处理程序时检查路径:
package main
import (
"fmt"
"log"
"net/http"
)
func index(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" { // Check path here
http.NotFound(w, req)
return
}
fmt.Fprintln(w, "index")
}
func foo(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "foo")
}
func bar(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "bar")
}
func main() {
mux := http.NewServeMux()
s := &http.Server{
Addr: ":8000",
Handler: mux,
}
mux.HandleFunc("/foo", foo)
mux.HandleFunc("/bar", bar)
mux.HandleFunc("/", index)
log.Fatal(s.ListenAndServe())
}
从 Go 1.22 开始,您现在可以使用
/
模式仅匹配 /{$}
示例:
package main
import (
"fmt"
"log"
"net/http"
)
func index(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "index")
}
func main() {
mux := http.NewServeMux()
s := &http.Server{
Addr: ":8000",
Handler: mux,
}
mux.HandleFunc("/{$}", index)
log.Fatal(s.ListenAndServe())
}