使用 Go Gin 读取请求正文中的文件

Read file in request body with Go Gin

当我尝试使用 Go Gin 读取我的 HTTP 请求的请求正文时,我得到的是空文件。根据我的请求,我发送了一个附加到请求正文的文件(内容类型:application/octet-stream)。

Request Headers
Authorization: Bearer XXX
User-Agent: PostmanRuntime/7.29.0
Accept: */*
Postman-Token: XXX
Host: localhost:8080
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 12
Content-Type: application/octet-stream
Request Body
src: "Path to my file"

后端 Go 代码:

bodySize, _ = strconv.ParseInt(c.Request.Header.Get("Content-Length"), 10, 64)
buf := bytes.NewBuffer(make([]byte, 0, bodySize))
_, err = io.Copy(buf, c.Request.Body)
fmt.Println(buf.String())

打印语句打印空字符串但文件不为空(内容长度为12)。

@novalagung yes, I'm reading it in a middleware before the main function, after the middleware the execution continues with c.Next() . In the middleware the reading works fine. –

阅读内容后http.Request.Body将为空。读取后需要将请求体存储在某个地方,因此不需要读取两次。


或者,还有另一种解决方法,您可以在阅读后将内容放回req.Body

// middleware do read the body
bodyBytes, _ := ioutil.ReadAll(req.Body)
req.Body.Close()  //  must close

// put back the bodyBytes to req.Body
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

但我不推荐!