gin-get路由和传参 - Go语言中文社区

gin-get路由和传参


1 .获取路径中参数

1 .传入http://localhost:8080/post/12312
2 .识别出12312
3 ./post/ ==/post xx
4 ./post/123123/123 XX
5 ./post xx 以上这几个都不能靠这个路由访问到
r.GET("/user/:name",func(c *gin.Context){
        name:=c.Param("name")
        c.JSON(200,gin.H{
            "msg":name,
        })
    })

2 .最简单的路由

r.GET("/post",func(c *gin.Context){
        c.json(200,gin.H{
            "msg":"post",
        })
    })
1 ./post
2 ./post/
3 .这个会匹配到这俩

3 .高级动态路由:匹配到第三层

r.GET("/post/:name/*action",func(c *gin.Context){
        name:=c.Param("name")
        action:=c.Param("action")
        message:=name+"is"+action
        c.String(http.StatusOK,message)
    })
1 ./post/name/
2 ./post/name/action 这俩都是可以匹配到

路由组:

v1:=r.Group("/v1")
    {
        v1.GET("/login",func(c *gin.Context){
            c.JSON(200,gin.H{
                "name":"/login",
            })
        })

        v1.GET("/p/:name/*action",func(c *gin.Context){
            // 这里必须嵌套一层
            name:=c.Param("name")
            c.JSON(200,gin.H{
                "name":name,
            })
        })
    }
1 .上面高级路由实现的不是可以通过路由组实现吗
2 .[http://localhost:8080/v1/p/asdfasdf/asdfas](http://localhost:8080/v1/p/asdfasdf/asdfas)

url参数查询

1 ./welcome?firstname=Jane&lastname=Doe

r.GET("/welcome",func(c *gin.Context){
        firstName:=c.DefaultQuery("firstname","Guest")
        // 后面是没有的默认值
        lastName:=c.Query("lastname")
        c.String(http.StatusOK,"hello %s %s",firstName,lastName)
    })
[http://localhost:8080/welcome?firstname=libater&lastname=skoll&littlename=sdfasdf](http://localhost:8080/welcome?firstname=libater&lastname=skoll&littlename=sdfasdf)
2. 那其实按照这种方式可以无限制的加参数的
3 .

form没有填method=post参数的时候

// 获取post参数:get+post混合,当form没有填method参数的时候
    r.GET("/post",func(c *gin.Context){
        name:=c.Query("name")
        c.JSON(200,gin.H{
            "status":"posted",
            "name":name,
        })
    })
1 .这样实际提交生成的网址是这个 [http://localhost:8080/post?name=1123&age=123](http://localhost:8080/post?name=1123&age=123)

版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/86781675f55e
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-12 12:04:34
  • 阅读 ( 1379 )
  • 分类:Go Web框架

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢