教程 > Gin 教程 > Gin 基础 阅读:79

Gin 获取参数

在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()
}

查看笔记

扫码一下
查看教程更方便