将 []net.Conn 传递给 io.MultiWriter

huangapple go评论107阅读模式
英文:

Passing []net.Conn to io.MultiWriter

问题

我有很多net.Conn,我想实现多个写入器,这样我就可以将数据发送到每个可用的net.Conn

我目前的方法是使用io.MultiWriter

func route(conn, dst []net.Conn) {
	targets := io.MultiWriter(dst[0], dst[1])

	_, err := io.Copy(targets, conn)
	if err != nil {
		log.Println(err)
	}
}

但问题是,我必须在io.MultiWriter中指定每个net.Conn的索引,这将是一个问题,因为切片的大小是动态的。

当我尝试通过将[]net.Conn传递给io.MultiWriter来尝试另一种方法时,像下面的代码一样

func route(conn, dst []net.Conn) {
    targets := io.MultiWriter(dst...)

    _, err := io.Copy(targets, conn)
    if err != nil {
        log.Println(err)
    }
}

会出现错误"cannot use mirrors (variable of type []net.Conn) as []io.Writer value in argument to io.MultiWriter"

有没有适当的方法来处理这种情况?这样我就可以将net.Conn切片传递给io.MultiWriter

谢谢。

英文:

I have many of net.Conn and i want to implement multi writer. so i can send data to every available net.Conn.

My current approach is using io.MultiWriter.

func route(conn, dst []net.Conn) {
	targets := io.MultiWriter(dst[0], dst[1])

	_, err := io.Copy(targets, conn)
	if err != nil {
		log.Println(err)
	}
}

but the problem is, i must specify every net.Conn index in io.MultiWriter and it will be a problem, because the slice size is dynamic.

when i try another approach by pass the []net.Conn to io.MultiWriter, like code below

func route(conn, dst []net.Conn) {
    targets := io.MultiWriter(dst...)

    _, err := io.Copy(targets, conn)
    if err != nil {
        log.Println(err)
    }
}

there is an error "cannot use mirrors (variable of type []net.Conn) as []io.Writer value in argument to io.MultiWriter"

Is there proper way to handle this case? so i can pass the net.Conn slice to io.MultiWriter.

Thank you.

答案1

得分: 1

io.MultiWriter() 的参数类型是 ...io.Writer,因此你只能传递类型为 []io.Writer 的切片。

所以首先创建一个正确类型的切片,将 net.Conn 的值复制到其中,然后像这样传递它:

ws := make([]io.Writer, len(dst))
for i, c := range dst {
    ws[i] = c
}

targets := io.MultiWriter(ws...)
英文:

io.MultiWriter() has a param of type ...io.Writer, so you may only pass a slice of type []io.Writer.

So first create a slice of the proper type, copy the net.Conn values to it, then pass it like this:

ws := make([]io.Writer, len(dst))
for i, c := range dst {
	ws[i] = c
}

targets := io.MultiWriter(ws...)

huangapple
  • 本文由 发表于 2022年3月18日 14:50:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/71523364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定