How to deal with io.EOF in a bytes.Buffer stream?
<p><a href="https://play.golang.org/p/JKXKa7Pvjd" rel="nofollow">https://play.golang.org/p/JKXKa7Pvjd</a></p>

<p>I am trying to figure out how I can test my background function where there can be random io.EOF in a stream using a bytes.Buffer?</p>

<p>Example:</p>

<pre><code>package main

import (
    "fmt"
    "io"
    "bytes"
    "time"
)

func main() {
    buffer := new(bytes.Buffer)
    go background(buffer)
    i := 0
    for i &lt; 5 {
        i++
        fmt.Fprintf(buffer, "%d)teststring\n", i)
        time.Sleep(1 * time.Second) // generates a io.EOF

    }
    time.Sleep(1 * time.Second)
}

func background(r io.Reader) {
    buf := make([]byte, 64)
    for {   
        n, err := r.Read(buf)
        if err != nil {
            fmt.Print(err.Error())
            return // removing `return` will result in race condition
        }
        fmt.Print(string(buf[:n]))
    }
}
</code></pre>

<p>The result I am looking for is:</p>

<pre><code>1)teststring
2)teststring
3)teststring
4)teststring
5)teststring
</code></pre>

<p>How can I achieve this using <code>time.Sleep(1 * time.Second)</code> to simulate latency?</p>