Golang 从 net.TCPConn 读取字节

Golang Read Bytes from net.TCPConn

是否有 ioutil.ReadAll 的版本可以一直读取到 EOF 或读取 n 字节(以先到者为准)?

出于 DOS 的原因,我不能只从 ioutil.ReadAll 转储中取出前 n 个字节。

io.ReadFull 要么 io.LimitedReader 要么 http.MaxBytesReader.

如果您需要一些不同的东西,首先看看它们是如何实现的,通过调整行为来推出您自己的东西是微不足道的。

有两种选择。如果n是你要读取的字节数,r是连接。

选项 1:

p := make([]byte, n)
_, err := io.ReadFull(r, p)

选项 2:

p, err := io.ReadAll(&io.LimitedReader{R: r, N: n})

如果应用程序通常会填满缓冲区,则第一个选项更有效。

如果您正在读取 HTTP 请求正文,请使用 http.MaxBytesReader

有几种方法可以满足您的要求。您可以使用其中任何一个。

func ReadFull

func ReadFull(r Reader, buf []byte) (n int, err error)

ReadFull reads exactly len(buf) bytes from r into buf. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read.

func LimitReader

func LimitReader(r Reader, n int64) Reader

LimitReader returns a Reader 从 r 读取但在 n 字节后以 EOF 停止。底层实现是 *LimitedReader.

func CopyN

func CopyN(dst Writer, src Reader, n int64) (written int64, err error)

CopyN copies n bytes (or until an error) from src to dst. It returns the number of bytes copied and the earliest error encountered while copying. On return, written == n if and only if err == nil.

func ReadAtLeast

func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)

ReadAtLeast reads from r into buf until it has read at least min bytes. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read.