如何使路径“/”不匹配Golang net/http中所有其他不匹配的路径

问题描述 投票:0回答:2

我正在使用 golang

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
go
2个回答
5
投票

由于您使用的多路复用器会将

/
处理程序与任何未注册的处理程序相匹配,因此您必须在调用
/
路径的处理程序时检查路径:

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.