这两天发现一个有意思的情况,好像 gin 框架里 c.PostForm() 函数只能从表单中获取参数,不能从 body 中解析表单参数,也就是说你如果用 c.PostForm() 来解析获取参数,客户端发起请求时,如果参数放在表单里,服务端能正常获取到参数,但是如果客户端把参数放在 body 里,即使 header 里配置了 ​​content-type:multipart/form-data​​,服务端仍就无法获取到参数。下面是检验过程:

服务端代码

package main

import (
"bytes"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
)

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

router.POST("/test", func(c *gin.Context) {
// 打印出 body
data, _ := ioutil.ReadAll(c.Request.Body)
fmt.Printf("req.body=%s\n, content-type=%v\n", data, c.ContentType())
// 把字节流重新放回 body 中
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data))
// 获取参数
userName := c.PostForm("user_name")
age := c.PostForm("age")
fmt.Printf("userName=%s, age=%s\n", userName, age)
c.JSON(200, "success")
})
router.Run(":8080")
}

postman 发起请求

使用 表单传递参数

golang gin 框架读取无法用 body 传递的表单参数_表单

查看服务端控制台,打印出了 form-data 格式的 body,也打印出了userName 和 age 参数,通过输出内容可以看出请求体的 content-type 是 ​​multipart/form-data​

golang gin 框架读取无法用 body 传递的表单参数_表单_02

使用 body 传参,并配合 header 里配置 ​​content-type:multipart/form-data​

golang gin 框架读取无法用 body 传递的表单参数_服务端_03

golang gin 框架读取无法用 body 传递的表单参数_获取参数_04

查看服务端控制台,发现 body内容这次不再是 form-data 格式,而是 json字符串的形式,即使打印出的 content-type 为 ​​multipart/form-data​​ 表明了我们所传递的参数类型确实是表单类型,但是参数还是没有获取成功

golang gin 框架读取无法用 body 传递的表单参数_服务端_05

仔细看其实控制台有一条 error 信息​​error on parse multipart form array: no multipart boundary param in Content-Type​​, 中文意思是转换表单数组时发生错误,在当前 content-type 下,没有可以转换的表单参数。说明服务端确实识别到了 content-type 是表单类型,但是在对 body 按照表单形式获取参数时,解析失败了。这样就验证了 c.PostForm() 函数只能从表单中获取参数,不能从 body 中解析表单参数。

by the way

1、c.Request.Body 是一个 io.CloseReader 类型,并不是字节数组类型或者字符串类型,所以如果想获取到真实 body 内容,还需要通过 ioutil.ReadAll() 来获取。

2、通过 ioutil.ReadAll() 来读取完 body 内容后,body 就为空了,为了后面能继续从 body 中获取参数,需要通过 ​​c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data))​​ 将字节数组重新返回到 body 中。

data, _ := ioutil.ReadAll(c.Request.Body)
fmt.Printf("req.body=%s\n, content-type=%v\n", data, c.ContentType())
// 把字节流重新放回 body 中
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data))

参考

​Gin框架body参数获取​

​Gin中间件打印request.Body​