Why does io.Copy sometimes lose lines when reading from a socket?
Solution 1:
bufio.Reader
implements buffering for an io.Reader
object. What does this mean? If you use a bufio.Reader
to read from an io.Reader
source, it may read more data from its source (and buffer it) than what you read directly from the bufio.Reader
itself.
This means if you use a bufio.Reader
to read from the sock
first, and then you use io.Copy()
, there may be some data already read from sock
and sitting in the bufio.Reader
's internal buffer, which io.Copy()
will not see and will not copy.
You shouldn't mix those 2 on the same io.Reader
source. If you must, then be sure to first drain the bufio.Reader
's buffer, then proceed to copy from sock
like this:
// First drain the buffer:
n, err := io.Copy(os.Stdout, rdr)
// Handle error
// Then proceed with the socket:
n, err = io.Copy(os.Stdout, sock)
// Handle error