Read file in request body with Go Gin


I’m getting empty file when I try to read the request body of my HTTP request using Go Gin. On my request I’m sending a file attached to the Request Body (Content Type: 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"

Backend Go code:

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)

The print sentence prints empty string but the file is not empty (Content Length is 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. –

The http.Request.Body will be empty after you read its content. You will need to store the request body somewhere after being read, so you do not need to read it twice.

Or, there is another alternative workaround, you can put back the content into the req.Body after being read.

// 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))

But I do not recommend it!

Answered By – novalagung

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.