Golang rewrites http request body

I am writing an http interceptor in the Golang on the server side. I can read the body of the http request from r.Body. Now, if I want to change the contents of the body, how can I change the body of the request 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)
}
+4
source share
1 answer

Body io.ReadCloser

It seems that the only way is to replace Bodywith an object that matches io.ReadCloser. To do this, you need to build the object Bodyusing any function that returns the object io.Readerand ioutil.NopCloserto enable the io.Readerobject io.ReadCloser.

bytes.NewBufferString

NewBufferString , s . .

strings.NewReader ( )

NewReader s. bytes.NewBufferString, .

ioutil.NopCloser

NopCloser ReadCloser no-op Close, Reader r.

new_body_content := "New content."
r.Body = ioutil.NopCloser(strings.NewReader(new_body_content))

, Request, Body. ContentLength:

r.ContentLength = int64(len(new_body_content))

, Body, TransferEncoding.

+6
source

Source: https://habr.com/ru/post/1615020/


All Articles