【问题标题】:How to get matched route in context in Gin?如何在杜松子酒的上下文中获得匹配的路线?
【发布时间】:2021-08-05 15:21:55
【问题描述】:

我有这个代码:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.New()
    r.GET("/user/:id", func(c *gin.Context) {
        // How can I get the litteral string "/user/:id" here ?
        c.JSON(http.StatusOK, gin.H{"message": "received request"})
    })
}

有什么方法可以在处理程序中检索文字字符串/user/:id?如果我使用c.Request.Path,它将为我提供路径的完整输出,例如/user/10

【问题讨论】:

  • 没有简单的方法,为什么需要那个字符串?
  • 没有办法,你需要做一些神奇的东西,例如将所有路线保存在地图上,并将该地图与当前 URL 进行比较(你需要将参数替换为它们的路线值寿)

标签: go go-gin


【解决方案1】:

根据文档,您可以使用FullPath()

router.GET("/user/:id", func(c *gin.Context) {
    c.FullPath() == "/user/:id" // true
})

【讨论】:

  • (嗨 - 没有必要删除你的上一篇文章;我只是想指出其他方法可用)
  • 如我所愿。 100% 正确。
猜你喜欢
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-24
  • 2019-04-13
  • 2013-01-20
  • 2022-11-24
  • 2020-06-06
相关资源
最近更新 更多