教程 > gin 教程 > 阅读:115

gin 获取参数——迹忆客-ag捕鱼王app官网

在gin框架中,可以通过query来获取url中 ? 后面所携带的参数。例如 /webname=迹忆客&website=www.jiyik.com。获取方法如下

package main
import (
    "github.com/gin-gonic/gin"
    "net/http"
)
func main() {
    r := gin.default()
    r.get("/", func(c *gin.context) {
        webname := c.query("webname")
        website := c.query("website")
        c.json(http.statusok, gin.h{
            "webname": webname,
            "website":  website,
        })
    })
    r.run()
}

运行结果如下

gin 获取参数


获取form参数

当前端请求的数据通过 form 表单提交时,例如向 /user/reset 发送了一个post请求,获取请求数据方法如下

package main
import (
    "net/http"
    "github.com/gin-gonic/gin"
)
func main() {
    r := gin.default()
    r.loadhtmlfiles("./login.html", "./index.html") //加载页面
    r.get("/", func(c *gin.context) {
        c.html(http.statusok, "login.html", nil)
    })
    r.post("/", func(c *gin.context) {
        username := c.postform("username") //对应h5表单中的name字段
        password := c.postform("password")
        c.html(http.statusok, "index.html", gin.h{
            "username": username,
            "password": password,
        })
    })
    r.run()
}

获取path参数

请求的参数通过url路径传递,例如/user/admin,获取请求url路径中的参数方法如下

package main
import (
    "net/http"
    "github.com/gin-gonic/gin"
)
func main() {
    r := gin.default()
    r.get("/user/:username", func(c *gin.context) {
        username := c.param("username")
        c.json(http.statusok, gin.h{
            "username": username,
        })
    })
    r.run()
}

查看笔记

扫码一下
查看教程更方便
网站地图