Writing a line-based TCP server
In this recipe, we will look at a TCP server that works with lines instead of bytes. There are some points you need to be careful about when reading lines from a network connection, especially related to the security of the server. Just because you are expecting to read lines does not mean the client will send well-formed lines.
How to do it...
- Use the same structure to set up the server as given in the previous section.
- In the connection handler, use a
bufio.Reader
orbufio.Scanner
to read lines. - Wrap the connection with an
io.LimitedReader
to limit line length.
Let’s take a look at how this can work. The following example shows how a connection handler can be implemented:
// Limit line length to 1KiB. const MaxLineLength = 1024 func handleConnection(conn net.Conn) error { defer conn.Close() // Wrap the connection with a limited reader // to prevent the client from sending unbounded...