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