如何处理在bytes.Buffer流中出现的io.EOF?

4

https://play.golang.org/p/JKXKa7Pvjd

我正在尝试弄清如何测试后台函数,其中流中可能存在随机的 io.EOF,使用 bytes.Buffer 可以实现?

例如:

package main

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

func main() {
    buffer := new(bytes.Buffer)
    go background(buffer)
    i := 0
    for i < 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]))
    }
}

我需要的结果是:
1)teststring
2)teststring
3)teststring
4)teststring
5)teststring

我该如何使用time.Sleep(1 * time.Second)来模拟延迟?
1个回答

7

你确定要使用 bytes.Buffer 吗?它不是流也不是线程安全的,这就是为什么会出现竞争条件。请使用 io.Pipe()

https://play.golang.org/p/c0fLEI350w

package main

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

func main() {
    pr, pw := io.Pipe()
    go background(pr)
    i := 0
    for i < 5 {
        i++
        fmt.Fprintf(pw, "%d)teststring\n", i)
        time.Sleep(1 * time.Second)

    }
    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
        }
        fmt.Print(string(buf[:n]))
    }
}

字节缓冲区是我唯一知道的东西:D 谢谢,我要去玩它了,看起来正是我需要的:D - Gert Cuykens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接