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

I tried something like this:

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

But Jin does not allow this and panic at startup.

The idea is to write middleware to handle this case, but ...

+6
source share
1 answer

I have success. Hope this helps 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)) } 

Launch example

 $ curl http://127.0.0.1:8081/example/log Log All $ curl http://127.0.0.1:8081/example/abc/log Log Specific, abc! 
+7
source

Source: https://habr.com/ru/post/1011887/


All Articles