我正在try 对我的网络应用程序运行一些测试.我想避免 for each 测试创建一个插槽,所以我想使用标准库中的io.Pipe个.但它只提供io.PipeReaderio.PipeWriter对.我需要两个相连的io.ReadWriteClosers

func TestEndpoints() {
    // Create pipeEndpoint1 and pipeEndpoint2. Both should implement  
    // io.ReadWriteCloser

    e1 := makeEndpoint(pipeEndpoint1)
    e2 := makeEndpoint(pipeEndpoint2)

    // Run some test
}
 
func makeEndpoint(rwc io.ReadWriteCloser) *Endpoint {
    // 
}

有没有方法创建两个相连的io.ReadWriteClosers?

推荐答案

在标准库中似乎没有方法可以做到这一点,所以这就是我所做的:

type PipeBidirectional struct {
    r *io.PipeReader
    w *io.PipeWriter
}

func NewPipes() (*PipeBidirectional, *PipeBidirectional) {
    r1, w1 := io.Pipe()
    r2, w2 := io.Pipe()

    return &PipeBidirectional{r1, w2}, &PipeBidirectional{r2, w1}
}

func (p *PipeBidirectional) Read(b []byte) (int, error) {
    return p.r.Read(b)
}

func (p *PipeBidirectional) Write(b []byte) (int, error) {
    return p.w.Write(b)
}

func (p *PipeBidirectional) Close() error {
    e1 := p.r.Close()
    e2 := p.w.Close()
    if e1 != nil || e2 != nil {
        return fmt.Errorf("e1: %w e2: %w", e1, e2)
    }
    return nil
}

Go相关问答推荐

无法找到与golang、nginx和postquist进行的docker-compose./主要

如何使用GRPC UnaryClientInterceptor中的`maily`参数?

Go GORM创建表,但不创建列

如何在围棋中从多部分.Part中获取多部分.文件而不保存到磁盘?

如何在gofiber/websocket/v2中设置状态代码和原因

Python样式生成器实现为通道:过早读取

如何创建在responseWriter.Write 上返回错误的http.ResponseWriter 模拟实例?

Golang telegram 机器人

在 go 中,将接收器 struct 从值更改为指针是否向后兼容?

杜松子wine 和中间件

一个Go module可以和之前的非module模块发布在同一个路径下吗?

我在 go 中制作的递归函数有什么问题?

设置指向空接口的指针

Go Colly 如何找到请求的元素?

在 Go 模板中对照片使用随机 Int

在 Gorm 的 AfterFind() 钩子中获取智能 Select struct 的值

Golang计算 struct struct 中的字段数

递归数据 struct 解组在 Go Lang Protobuf 中给出错误无法解析无效的线格式数据

如何在测试中传递用户名和密码等参数

空接口与泛型接口有何不同?