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 ...
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With