Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle these routes: /example/log and /example/:id/log?

Tags:

go

go-gin

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 ...

like image 687
Zender Fufikoff Avatar asked Oct 31 '16 13:10

Zender Fufikoff


1 Answers

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!
like image 126
Aminadav Glickshtein Avatar answered Sep 22 '22 07:09

Aminadav Glickshtein