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 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合