首页 > 解决方案 > 如何在 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))
}

标签: httpgohttprouter

解决方案


您可以删除该行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")
    }
}

推荐阅读