Copy from an io Reader in chunks

I am quite new to Golang and am experimenting with API creation. To create a mock endpoint, I want to take my request body, and copy it to a discard writer in chunks, while sleeping a brief amount of time in between each read.
I currently have a function which copies the body to a discard writer in one go:
_, err := io.Copy(io.Discard, r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
but want to do something more like CopyN(io.Discard, r.Body, 10)
in a loop and sleep after each chunk.
I can't find great documentation on how to do this, any advice would be greatly appreciated!
Answer
Use the for
statement to call CopyN(io.Discard, r.Body, 10)
in a loop and sleep after each chunk.
for {
_, err := io.CopyN(io.Discard, r.Body, 10)
if err == io.EOF {
// Body successfully discarded.
break
} else if err != nil {
log.Fatal(err)
}
time.Sleep(time.Second)
}
Enjoyed this question?
Check out more content on our blog or follow us on social media.
Browse more questions