http - 如何在 go httprouter: /hello/:name 和 /hello/b/c 中处理这些路由?
问题描述
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))
}
解决方案
您可以删除该行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")
}
}
推荐阅读
- html - 负数 (CSS) 被编译为正数
- ruby - 如何将数组转换为字符串?
- python - 带有所有附加功能的“pip install”
- c++ - 小数作为 unordered_map 的键
- firebase - FlutterFire Crashlytics 错误:配置项目“:app”时出现问题
- r - 提取字符串的坐标对
- python - python loadtxt来自许多文件,附加到相同的numpy数组中
- python - 获取随机生成数学计算内容的Python代码
- aws-iot - 如何限制 AWS-IoT 事物发布/订阅 AWS IoT-Core 中的某些主题?
- postgresql - 服务器和 postgresql 在 Docker `getaddrinfo ENOTFOUND` 上运行时无法连接