httprouter不允许这一点,并在开始时惊慌。
httprouter :恐慌:通配符路由:名称与路径'/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))
}发布于 2021-09-13 16:43:43
您可以删除行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")
}
}https://stackoverflow.com/questions/69165880
复制相似问题