英文:
How to discard any incoming data in a connection in Go?
问题
我正在向远程服务器发送一个请求,但不关心它的响应。我不想直接关闭连接,因为如果这样做,服务器会出现"Broken pipe"错误。
我目前使用一个缓冲区循环调用Read()方法:
con, _ := net.Dial("tcp", host)
// ...
data := make([]byte, 512)
for {
if _, err = con.Read(data); err == io.EOF {
break
}
}
但我想要的是类似于Bash中的>/dev/null
的效果。我找到了ioutils.Discard
,但它是一个io.Writer
,而con.Read
只能在[]byte
缓冲区上工作。
有没有比我目前做的读取缓冲区更高效的方法?
英文:
I’m sending a request to a remote server, but don’t care about its response. I don’t want to close the connection directly because the server gets a Broken pipe
error if I do that.
I currently loop on Read() calls with a buffer:
con, _ := net.Dial("tcp", host)
// ...
data := make([]byte, 512)
for {
if _, err = con.Read(data); err == io.EOF {
break
}
}
But I’m looking for something like >/dev/null
in Bash. I’ve found ioutils.Discard
, but it’s an io.Writer
and con.Read
only works on a []byte
buffer.
Is there a more efficient way than just reading in a buffer like what I’m currently doing?
答案1
得分: 33
你需要像这样使用ioutil.Discard
:
io.Copy(ioutil.Discard, con)
io.Copy
函数从源io.Reader
复制到目标io.Writer
。
func Copy(dst Writer, src Reader) (written int64, err error)
。
io.Reader
是一个接口,定义如下:
type Reader interface {
Read(p []byte) (n int, err error)
}
io.Writer
是一个接口,定义如下:
type Writer interface {
Write(p []byte) (n int, err error)
}
net.Conn
实现了io.Reader
接口,而ioutil.Discard
实现了io.Writer
接口。
英文:
you have to use ioutil.Discard
like this
io.Copy(ioutil.Discard, con)
io.Copy
copies from a src io.Reader
to a io.Writer
func Copy(dst Writer, src Reader) (written int64, err error)
io.Reader is an interface defined as
type Reader interface {
Read(p []byte) (n int, err error)
}
io.Writer
type Writer interface {
Write(p []byte) (n int, err error)
}
net.Conn
implements io.Reader
and ioutil.Discard
implements io.Writer
答案2
得分: 9
自Go 1.16(2021年2月)起,程序应该使用io.Discard
:
package main
import (
"fmt"
"io"
)
func main() {
fmt.Fprint(io.Discard, "hello world")
}
https://golang.org/pkg/io#Discard
英文:
Since Go 1.16 (Feb 2021), programs should be using io.Discard
:
package main
import (
"fmt"
"io"
)
func main() {
fmt.Fprint(io.Discard, "hello world")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论