Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Go, how can I reuse a ReadCloser?

Tags:

go

I have a http request which I need to inspect the body of. But when I do, the request fails. I'm assuming this had to do with the Reader needing to be reset, but googling along the lines of go ioutil reset ReadCloser hasn't turned anything up that looks promising.

c is a *middleware.Context, c.Req.Request is a http.Request, and c.Req.Request.Body is an io.ReadCloser

contents, _ := ioutil.ReadAll(c.Req.Request.Body)
log.Info("Request: %s", string(contents))
proxy.ServeHTTP(c.RW(), c.Req.Request)

Specifically the error I get is http: proxy error: http: ContentLength=133 with Body length 0

like image 662
Camden Narzt Avatar asked Dec 19 '22 22:12

Camden Narzt


1 Answers

You can't reset it, because you've already read from it and there's nothing left in the stream.

What you can do is take the buffered bytes you already have, and replace the Body with a new io.ReadCloser

contents, _ := ioutil.ReadAll(c.Req.Request.Body)
log.Info("Request: %s", string(contents))
c.Req.Request.Body = ioutil.NopCloser(bytes.NewReader(contents))
proxy.ServeHTTP(c.RW(), c.Req.Request)
like image 54
JimB Avatar answered Jan 15 '23 10:01

JimB