首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在go httprouter: /hello/:name和/hello/b/c中处理这些路由?

如何在go httprouter: /hello/:name和/hello/b/c中处理这些路由?
EN

Stack Overflow用户
提问于 2021-09-13 16:05:36
回答 1查看 266关注 0票数 0

httprouter不允许这一点,并在开始时惊慌。

httprouter :恐慌:通配符路由:名称与路径'/hello/:name‘中现有子节点的冲突。

据我所知,

"/hello/:name“有两个部分,但是/hello/b/c有三个部分。

" /hello /:name“将与任何url匹配,其中有两个前缀为/hello的部分

" /hello/b/c“只匹配/hello/b/c

代码语言:javascript
复制
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))
}
EN

回答 1

Stack Overflow用户

发布于 2021-09-13 16:43:43

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

代码语言:javascript
复制
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")
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69165880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档