0

httprouter 不允许这样做,并且在启动时会出现恐慌。

httprouter :panic: 通配符路由 ':name' 与路径 '/hello/:name' 中的现有子级冲突。

在我的理解中,
"/hello/:name" 有两个部分,但是 /hello/b/c 有三个部分。
"/hello/:name" 将匹配任何 url 有两个前缀 /hello
"/hello/b/c" 只匹配 /hello/b/c

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!\n")
}

func Index2(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome222!\n")
}

func main() {
    router := httprouter.New()
    router.GET("/hello/b/c", Index2)

    router.GET("/hello/:name", Index)

    log.Fatal(http.ListenAndServe(":8080", router))
}
4

1 回答 1

0

您可以删除该行router.GET("/hello/b/c", Index2),然后有:

func Index(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    if strings.HasPrefix(ps.ByName("name"), "b/c") {
        return Index2(w, r, ps)
    } else {
        fmt.Fprint(w, "Welcome!\n")
    }
}
于 2021-09-13T16:43:43.800 回答