当前位置:网站首页>go : gin路径参数

go : gin路径参数

2022-07-22 17:58:00 IT工作者

本文介绍 gin框架下如何获取路径参数

代码:

package main

import (
    "net/http"

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

func main() {
    router := gin.Default()

    // This handler will match /user/john but will not match /user/ or /use
    router.GET("/user/:name", func(c *gin.Context) {
        name := c.Param("name")
        c.String(http.StatusOK, "Hello %s", name)
    })

    // However, this one will match /user/john/ and also /user/john/send
    // If no other routers match /user/john, it will redirect to /user/john/
    router.GET("/user/:name/*action", func(c *gin.Context) {
        name := c.Param("name")
        action := c.Param("action")
        message := name + " is " + action
        c.String(http.StatusOK, message)
    })

    router.Run(":8080")
}

运行代码

客户端访问

->curl  localhost:8080/user/world
Hello world->
->curl  localhost:8080/user/world123
Hello world123->
->curl  localhost:8080/user/world/123
world is /123->
原网站

版权声明
本文为[IT工作者]所创,转载请带上原文链接,感谢
https://cloud.tencent.com/developer/article/2054719