如何处理这些路由:/example/log 和 /example/:id/log?

huangapple go评论122阅读模式
英文:

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

问题

我尝试了类似这样的代码:

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

但是 Gin 不允许这样做,并在启动时出现错误。

一个想法是编写一个中间件来处理这种情况,但是...

英文:

I tried something like this:

  1. router.GET("/example/log", logAllHandler)
  2. 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 ...

答案1

得分: 8

我已经成功完成了。希望这对你有所帮助:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/julienschmidt/httprouter"
  5. "log"
  6. "net/http"
  7. )
  8. func logAll(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  9. if ps.ByName("id") == "log" {
  10. fmt.Fprintf(w, "Log All")
  11. }
  12. }
  13. func logSpecific(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  14. fmt.Fprintf(w, "Log Specific, %s!\n", ps.ByName("id"))
  15. }
  16. func main() {
  17. router := httprouter.New()
  18. router.GET("/example/:id", logAll)
  19. router.GET("/example/:id/log", logSpecific)
  20. log.Fatal(http.ListenAndServe(":8081", router))
  21. }

运行示例:

  1. $ curl http://127.0.0.1:8081/example/log
  2. Log All
  3. $ curl http://127.0.0.1:8081/example/abc/log
  4. Log Specific, abc!
英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/julienschmidt/httprouter"
  5. "log"
  6. "net/http"
  7. )
  8. func logAll(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  9. if ps.ByName("id") == "log" {
  10. fmt.Fprintf(w, "Log All")
  11. }
  12. }
  13. func logSpecific(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  14. fmt.Fprintf(w, "Log Specific, %s!\n", ps.ByName("id"))
  15. }
  16. func main() {
  17. router := httprouter.New()
  18. router.GET("/example/:id", logAll)
  19. router.GET("/example/:id/log", logSpecific)
  20. log.Fatal(http.ListenAndServe(":8081", router))
  21. }

Example of running

  1. $ curl http://127.0.0.1:8081/example/log
  2. Log All
  3. $ curl http://127.0.0.1:8081/example/abc/log
  4. Log Specific, abc!

huangapple
  • 本文由 发表于 2016年10月31日 21:48:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/40343515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定