gin框架 参数

web 程序中经常需要处理各种形式的参数,参数是处理 HTTP 请求中很重要的工作,它是前端向后端提交数据的基本形式。

gin 框架内置了处理 HTTP 各种参数的方法,包括 API 参数,URL 参数 以及 表单参数的处理。

 

1. API 参数处理

gin 框架中,可以通过 Context 的 Param 方法来获取 API 参数。

比如:提取 http://localhost:8080/user/zhangsan 的参数 zhangsan。

package main

import (
    "net/http"
    "strings"

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

func main() {
    engine := gin.Default()
    engine.GET("/user/:name", func(c *gin.Context) {
        name := c.Param("name")
        c.String(http.StatusOK, "name=" + name)
    })

    // 监听8080端口
    engine.Run(":8080")
}

运行程序,浏览器中输入:http://localhost:8080/user/zhangsan,浏览器会输出:name=zhangsan。

 

2. URL 参数处理

URL 参数可以通过 DefaultQuery() 或 Query() 方法获取。

DefaultQuery() 若参数不存在,则返回默认值,Query()若不存在,返回空串。

package main

import (
    "fmt"
    "net/http"
    "github.com/gin-gonic/gin"
)

func main() {
    engine := gin.Default()
    engine.GET("/user", func(c *gin.Context) {
        // 指定默认值
        // http://localhost:8080/user 才会打印出来默认的值
        name := c.DefaultQuery("name", "编程教程")
        c.String(http.StatusOK, fmt.Sprintf("name=%s", name))
    })
    engine.Run()
}

运行程序,浏览器中输入:

  • http://localhost:8080/user,浏览器会输出:name=编程教程
  • http://localhost:8080/user?name=zhangsan,浏览器会输出:name=zhangsan。

 

3. 表单参数处理

表单传输为post请求,http常见的传输格式为四种:

  • application/json
  • application/x-www-form-urlencoded
  • application/xml
  • multipart/form-data

表单参数可以通过 PostForm() 方法获取,该方法默认解析的是 x-www-form-urlencoded 或 from-data 格式的参数。

package main

import (
    "fmt"
    "net/http"
    "github.com/gin-gonic/gin"
)

func main() {
    engine := gin.Default()
    engine.POST("/form", func(c *gin.Context) {
        types := c.DefaultPostForm("type", "post")
        username := c.PostForm("username")
        password := c.PostForm("userpassword")
        c.String(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", username, password, types))
    })
    engine.Run()
}

从表单中获取了 types、username、password 三个参数。

web 程序中有时候需要处理上传文件,通常由前端负责提交文件,后端负责处理或者保存文件。gin 框架内置了处理文件上传的方法,包括 单个文件,多个文件以及特定文件特殊文件的处理。上传单个文件:gin 框架中,multipart/form-data 格式用于文件上。文件上传与原生的 net/http 方法类似,不同在于 gin 把原生的 request 封装到 c.Request 中。