Why request.Body is empty after decoding or reading?

I came across a weird problem. Please see the code below:

var p Person

data, _ := ioutil.ReadAll(r.Body) //data will not be empty

json.NewDecoder(r.Body).Decode(&p) //it will be empty upon reading

fmt.Println(p.ID) //will be empty

json.NewDecoder(r.Body).Decode(&p) //will not be empty

body, _ := ioutil.ReadAll(r.Body) //it will be empty upon reading

fmt.Println(p.ID) //will not be empty

As you can see from the code, if I read the r.Body first, then check it, it is empty. Why does it become empty after reading from the IO stream?

Sorry, but from your code I can see, that the body seems to be available again after it has been disappeared already.

But I will just pretend your code isn’t there at all and I will assume, that you are talking about a requests body in an http-handler.

So r.Body is a io.ReadCloser, a readable stream of bytes, which is empty after it has been consumed. This is just how any io.Reader works.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.