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

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题