【问题标题】:How to handle these routes: /example/log and /example/:id/log?如何处理这些路由:/example/log 和 /example/:id/log?
【发布时间】:2016-11-01 02:17:48
【问题描述】:

我尝试过这样的事情:

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

但是 Gin 不允许这样做,并且在开始时会出现恐慌。

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

【问题讨论】:

  • 什么是恐慌日志?您的代码似乎没有错,因此我们需要有关恐慌的更多详细信息。
  •  [GIN-debug] GET /example/log --> main.logAllHandler (3 个处理程序) [GIN-debug] GET /example/:id/log --> main.logHandler (3 个处理程序)恐慌:通配符路由 ':id' 与路径 '/example/:id/log' 
    中的现有子级冲突
  • 所以 /:id/log 与 /log 冲突,所以我建议改用 /log/:id。我真的不知道为什么会发生冲突。
  • 如果你在 Github 上查看this issue,你会发现你并不孤单。我觉得换个大猩猩产品可能会更好pat。

标签: go go-gin


【解决方案1】:

我成功了。希望对您有所帮助:

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))
}

运行示例

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

【讨论】:

  • 很好的解释。但是,您可能需要考虑 goji 我发现这非常有用。
猜你喜欢
  • 2013-05-19
  • 2012-10-15
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
相关资源
最近更新 更多