I'm writing an http interceptor in Golang on the server side. I can read the http request body from r.Body
. Now If I want to modify the body content, how can I modify the request body before the control is passed to the next interceptor?
func(w http.ResponseWriter, r *http.Request) {
// Now I want to modify the request body, and
// handle(w, r)
}
Body io.ReadCloser
It seems like the only way is to substitute a Body
with an object appropriate to io.ReadCloser
interface. For this purpose you need to construct a Body
object using any function which returns io.Reader
object and ioutil.NopCloser
to turn the io.Reader
object to io.ReadCloser
.
bytes.NewBufferString
NewBufferString creates and initializes a new Buffer using string s as its initial contents. It is intended to prepare a buffer to read an existing string.
strings.NewReader
(used in an example below)
NewReader returns a new Reader reading from s. It is similar to bytes.NewBufferString but more efficient and read-only.
ioutil.NopCloser
NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.
new_body_content := "New content."
r.Body = ioutil.NopCloser(strings.NewReader(new_body_content))
But to be clear and not to confuse other parts of the application you need to change Request
attributes related to Body
content. Most of the time it is only ContentLength
:
r.ContentLength = int64(len(new_body_content))
And in a rare case, when your new content uses different encodings from original Body
, it could be TransferEncoding
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With