Gin 如何获取 POST 表单数据?

这章节的取名真难,本意是 如何获取 content-type 为 multipart/form-data 或者 application/x-www-form-urlencoded 表单数据。

这里的参数,是排除发起 POST 请求时放在 URL 中的那些查询字符串参数的。

与获取查询字符串参数类似的, Gin 也提供了三个类似的方法用于获取 POST 请求提交的参数,它们分别是 c.PostForm()、c.DefaultPostForm() 和 c.GetPostForm()。

三者的区别如下

方法 说明
c.PostForm() 获取 POST 表单参数,如果参数不存在或值为空则返回空字符串 ""
c.DefaultPostForm() 获取 POST 表单参数,如果参数不存在或值为空则返回第二个参数做为值
c.GetPostForm() 类似于 c.PostForm(),但同时返回第二个 bool 参数用于判断该参数到底存不存在

假设有以下这个 POST 请求

POST /post HTTP/1.1
Content-Type: application/x-www-form-urlencoded

id=1234&name=Manu&value=

三者的获取规则如下

c.PostForm()

c.PostForm("id")     // 返回 "1234"
c.PostForm("name")   // 返回 "Manu"
c.PostForm("value")  // 返回 ""
c.PostForm("wtf")    // 返回 ""

c.DefaultPostForm()

c.DefaultPostForm("id", "none")        // 返回 "123"   
c.DefaultPostForm("name", "unknown")   // 返回 "Manu"
c.DefaultPostForm("value")             // 返回 ""
c.DefaultPostForm("wtf", "none")       // 返回 "none" 注意和 c.Query() 的区别

c.GetPostForm()

c.GetPostForm("id")        // 返回 ("123",true)  
c.GetPostForm("name")   // 返回 ("Manu",true)
c.GetPostForm("value")             // 返回 ("",true)
c.GetPostForm("wtf")       // 返回 ("",false)  注意和 c.Query() 的区别

示例代码如下

package main

import (
    "net/http"

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

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

    router.POST("/form_post", func(c *gin.Context) {
        message := c.PostForm("message")
        nick := c.DefaultPostForm("nick", "anonymous")

        c.JSON(http.StatusOK, gin.H{
            "status":  "posted",
            "message": message,
            "nick":    nick,
        })
    })
    router.Run(":8080")
}
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

♥   简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.