I want to program a HTTP-Proxy in golang. I use this module for the proxy: https://github.com/elazarl/goproxy. When someone uses my proxy, it calls a function with an http.Response as an Input. Let's call it "resp". resp.Body is an io.ReadCloser. I can read from it into a []byte array by using it's Read Method. But then the contents of it are gone from the resp.Body. But I have to return an http.Response with the Body that I read into a []byte array. How can I do that?
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
}
You're going to have to read all of the body first, so you can properly close it. Once you have the entire body read, you can simply replace the 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))
That's because the io.Reader
acts more as a buffer, when you read it, you've consumed that data in the buffer and are left with an empty body. To solve that problem you just need to close the responses body and create a new ReadCloser
out of 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))