Golang Gin框架:从Context获取方法名和路由名
在Golang Gin框架中,可以使用gin.Context的Request属性来获取请求的方法名和路由名。
以下是示例代码:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/hello", helloHandler)
router.Run(":8080")
}
func helloHandler(c *gin.Context) {
method := c.Request.Method
path := c.Request.URL.Path
fmt.Printf("Method: %s\n", method)
fmt.Printf("Path: %s\n", path)
c.JSON(200, gin.H{
"message": "Hello, World!",
})
}
在这个示例中,我们创建了一个简单的Gin应用,并定义了一个GET请求的路由/hello,对应的处理函数是helloHandler。在helloHandler函数中,我们通过c.Request.Method和c.Request.URL.Path获取了请求的方法名和路由名,并使用fmt.Printf打印出来。
当我们运行这个示例程序并访问http://localhost:8080/hello时,会在控制台上输出类似以下的结果:
Method: GET
Path: /hello
这样就成功地从gin.Context中获取了方法名和路由名。
原文地址: http://www.cveoy.top/t/topic/fB96 著作权归作者所有。请勿转载和采集!