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 .
source
share