Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang rewrite http request body

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)
}
like image 333
Qian Chen Avatar asked Nov 09 '15 09:11

Qian Chen


1 Answers

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

Related attributes

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.

like image 158
I159 Avatar answered Nov 20 '22 16:11

I159