Golang Reading Bytes from net.TCPConn

Is there a version ioutil.ReadAllthat will be read until it reaches EOF OR if it reads nbytes (whichever comes first)?

I can’t just take the first nbytes from the dump ioutil.ReadAllfor DOS.

+4
source share
3 answers

io.ReadFull or io.LimitedReader or http.MaxBytesReader .

If you need something else to take a look at how they are implemented first, it would be trivial to steer your own with changed behavior.

+1
source

. .

func ReadFull

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

ReadFull len (buf) r buf. , . EOF, .

func LimitReader

func LimitReader(r Reader, n int64) Reader

LimitReader Reader, r, EOF n . - * LimitedReader.

func CopyN

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

CopyN n ( ) src dst. , . , == n , err == nil.

func ReadAtLeast

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

ReadAtLeast r buf , . , . EOF, .

+2

There are two options. If nis the number of bytes you want to read, and ris the connection.

Option 1:

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

Option 2:

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

The first option is more effective if the application usually fills the buffer.

If you are reading the body of an HTTP request, use http.MaxBytesReader .

+1
source

All Articles