I\'m a newbie with Go, but so far I\'m liking it very much.
I have a problem I can\'t figure out. I\'m migrating an API from Node to Go and there is this log where I
TIL that http.Response.Body
is a buffer, which means that once it has been read, it cannot be read again.
It's like a stream of water, you can see it and measure it as it passes but once it's gone, it's gone.
However, knowing this, there is a workaround, you need to "catch" the body and restore it:
// Read the Body content
var bodyBytes []byte
if context.Request().Body != nil {
bodyBytes, _ = ioutil.ReadAll(context.Request().Body)
}
// Restore the io.ReadCloser to its original state
context.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
// Continue to use the Body, like Binding it to a struct:
order := new(models.GeaOrder)
error := context.Bind(order)
Now, you can use context.Request().Body
somewhere else.
Sources:
http://grokbase.com/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-response-body-or-any-reader
https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361
I believe you can do this:
m := make(map[string]interface{});
if err := context.Bind(&m); err != nil {
return result, err
}
fmt.Println(m)