dongpang9573 2016-10-31 13:48 采纳率: 0%
浏览 40
已采纳

如何处理以下路由:/ example / log和/ example /:id / log?

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

  • 写回答

1条回答 默认 最新

  • duanqiang5722 2016-10-31 18:15
    关注

    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!
    ", 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!
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效