Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from a Reader multiple times

Tags:

io

go

I'm building a simple caching proxy that intercepts HTTP requests, grabs the content in response.Body, then writes it back to the client. The problem is, as soon as I read from response.Body, the write back to the client contains an empty body (everything else, like the headers, are written as expected).

Here's the current code:

func requestHandler(w http.ResponseWriter, r *http.Request) {
    client := &http.Client{}
    r.RequestURI = ""
    response, err := client.Do(r)
    defer response.Body.Close()
    if err != nil {
        log.Fatal(err)
    }
    content, _ := ioutil.ReadAll(response.Body)
    cachePage(response.Request.URL.String(), content)
    response.Write(w)
}

If I remove the content, _ and cachePage lines, it works fine. With the lines included, requests return and empty body. Any idea how I can get just the Body of the http.Response and still write out the response in full to the http.ResponseWriter?

like image 863
jeffknupp Avatar asked Jan 10 '23 18:01

jeffknupp


1 Answers

As in my comment you could implement the io.ReadCloser

As per Dewy Broto (Thanks) you can do this much simpler with:

content, _ := ioutil.ReadAll(response.Body)
response.Body = ioutil.NopCloser(bytes.NewReader(content))
response.Write(w)
like image 128
DanG Avatar answered Jan 22 '23 06:01

DanG