6

I tried something like this:

router.GET("/example/log", logAllHandler)
router.GET("/example/:id/log", logHandler)

But Gin does not allow this and panics upon start.

An idea is write a middleware to handle this case, but ...

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
  • What's the panic log? Your code doesn't seem wrong, so we need more details on the panic. – jnmoal Oct 31 '16 at 14:31
  • [GIN-debug] GET /example/log --> main.logAllHandler (3 handlers) [GIN-debug] GET /example/:id/log --> main.logHandler (3 handlers) panic: wildcard route ':id' conflicts with existing children in path '/example/:id/log' – Zender Fufikoff Oct 31 '16 at 14:35
  • So /:id/log conflicts with /log, so I suggest to use /log/:id instead. I don't really know why it's a conflict. – jnmoal Oct 31 '16 at 14:54
  • 1
    If you check [this issue](https://github.com/julienschmidt/httprouter/issues/12) on Github you will find you are not alone. I think it would better to change a gorilla product maybe [pat](http://www.gorillatoolkit.org/pkg/pat). – PumpkinSeed Oct 31 '16 at 15:15

1 Answers1

8

I have success to do it. Hope that it will help you:

package main

import (
    "fmt"
    "github.com/julienschmidt/httprouter"
    "log"
    "net/http"
)

func logAll(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    if ps.ByName("id") == "log" {
        fmt.Fprintf(w, "Log All")
    }
}

func logSpecific(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "Log Specific, %s!\n", ps.ByName("id"))
}

func main() {
    router := httprouter.New()
    router.GET("/example/:id", logAll)
    router.GET("/example/:id/log", logSpecific)

    log.Fatal(http.ListenAndServe(":8081", router))
}

Example of running

$ curl http://127.0.0.1:8081/example/log
Log All
$ curl http://127.0.0.1:8081/example/abc/log
Log Specific, abc!
Toni Villena
  • 633
  • 1
  • 12
  • 17
Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117