0

httprouter does not allow this and panics when start.

httprouter :panic: wildcard route ':name' conflicts with existing children in path '/hello/:name'.

In my understanding,
"/hello/:name" has two parts ,but /hello/b/c has three parts.
"/hello/:name" will match any url has two parts which prefix /hello
"/hello/b/c" only match /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))
}
mkopriva
  • 35,176
  • 4
  • 57
  • 71
桃桃桃子
  • 159
  • 1
  • 2
  • 7
  • `:name` in the second path conflicts with `b` in the first path. It doesn't matter how many segments the paths have, what matters is that their prefix is the same. And, as the error suggests, this is not allowed by `httprouter`. The solution is either A. to not use such paths, or B. to not use `httprouter` and instead use one that supports such paths. – mkopriva Sep 13 '21 at 16:13
  • if you want to match variable length paths of a single method, GET, with the same prefix - httprouter suggests the `*` syntax over `:`. So instead of `/hello/:name` you write `/hello/*name` which will now handle both `/hello/john` and `/hello/b/c` and anything else after `hello/` with the name param. Of course you may choose to use some library else entirely as @mkopriva suggests. – Kelsnare Sep 13 '21 at 20:10

1 Answers1

0

You could remove the line router.GET("/hello/b/c", Index2) and then have:

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")
    }
}
dave
  • 62,300
  • 5
  • 72
  • 93