Reading a buffer and rewriting it to http.Response in Go

I want to program a HTTP proxy in golang. I am using this proxy module: https://github.com/elazarl/goproxy . When someone uses my proxy, they call a function with http.Response as input. Let's call it "resp". resp.Body is io.ReadCloser. I can read from it into byte array [] using this read method. But then its content was removed from resp.Body. But I have to return the http.Response with the body that I read into the byte array []. How can i do this?

Greetings,

Max

My code:

proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {

   body := resp.Body
   var readBody []byte
   nread, readerr := body.Read(readBody)
   //the body is now empty
   //and i have to return a body
   //with the contents i read.
   //how can i do that?
   //doing return resp gives a Response with an empty body
}

      

+3


source to share


2 answers


You will need to read the entire body first so that you can close it properly. After you have read all of the text, you can simply replace Response.Body

with your buffer.



readBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
    // handle error
}
resp.Body.Close()
// use readBody

resp.Body = ioutil.NopCloser(bytes.NewReader(readBody))

      

+3


source


This is because it io.Reader

acts more like a buffer, when you read it you have used that data in the buffer and are left with an empty body. To solve this problem, you just need to close the response body and create a new one ReadCloser

from the body, which is now a string.



import "io/ioutil"

readBody, err := ioutil.ReadAll(resp.Body)

if err != nil {
     // 
}

resp.Body.Close()
resp.Body = ioutil.NopCloser(bytes.NewReader(readBody))

      

+1


source







All Articles