Reader can return partial data. From docs : "If some data is available but not len (p) bytes, Read usually returns what is available, rather than waiting for more."
This is a problem in any language, even if something like this happened to you in C: TCP just provides a byte stream that can be written at any time. Separate records can be split into several packets for transmission, and there is no built-in signal for the receiver telling where one record / message / request ends. The application must figure out its own path to the signal boundaries. This can mean delimiters ( \n ) or implicit or explicit byte counts (HTTP Content-Length is explicit).
To read a specific number of input bytes, you want io.ReadAtLeast or io.ReadFull . To read until an arbitrary condition is met, you simply have to loop through the Read call until there is an error. (Then you may need an error on too large inputs to prevent a bad client from using server resources.) If you are using a text protocol, you should consider net/textproto , which puts bufio.Reader before the connection, so you can read the lines. To limit how long you will wait to finish reading (so that a bad client cannot leave the scroll and use memory, etc. Forever), look at net with Deadline in the name (which are associated with Timeout functions in Error types). The context package helps manage timeouts, deadlines and cancellations, and is especially useful if, for example, you write a complex server that is going to perform many network operations for each request.
The sample code has a possibly unrelated, but important problem: it removes errors from Read and Write . This can mask simple problems and make debugging difficult. If you have problems after accounting for partial reads, check all errors before contacting for further assistance. Take a look errcheck so that errors like this do not get into production.
twotwotwo
source share