Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read request body twice in Golang middleware?

Tags:

In a middleware, I want to read request body to perform some checks. Then, the request is passed to the next middleware where the body will be read again. Here's what I do:

bodyBytes, _ := ioutil.ReadAll(req.Body)
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
// use bodyBytes
// pass to next middleware

Now, req.Body.Close will do nothing. Will it break since the previous req.Body.Close implementation did some connection handling?

like image 638
Sergey Avatar asked Oct 26 '17 07:10

Sergey


People also ask

How do you read HTTP request body in Golang?

In Go, you can use the io. ReadAll() function (or ioutil. ReadAll() in Go 1.15 and earlier) to read the whole body into a slice of bytes and convert the byte slice to a string with the string() function. To exclude the response body from the output, change the boolean argument to httputil.

How do you read a response body in Golang?

To read the body of the response, we need to access its Body property first. We can access the Body property of a response using the ioutil. ReadAll() method. This method returns a body and an error.


1 Answers

Will it break since the previous req.Body.Close implementation did some connection handling?

No.

But your code is buggy: You should close the req.Body once you are done reading all of it. Then you construct a new ReadCloser as you did and hand this to the next middleware (which itself or stuff further down is responsible for closing is.)

bodyBytes, _ := ioutil.ReadAll(req.Body)
req.Body.Close()  //  must close
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
like image 191
Volker Avatar answered Sep 16 '22 16:09

Volker