I have a TCP packet connection (net.Conn
) set up by listening on a port.
conn, err := ln.Accept()
I need to read the first UVarInt of the Conn.Read([]byte)
buffer, which starts at index 0.
Previously, I would only need the first byte, which is easy to do using
packetSize := make([]byte, 1)
conn.Read(packetSize)
// Do stuff with packetSize[0]
However, as previously mentioned, I need to get the first UVarInt I can reach using the net.Conn.Read() method. Keep in mind that a UVarInt can have pretty much any length, which I cannot be sure of (the client doesn't send the size of the UVarInt). I do know however that the UVarInt starts at the very beginning of the buffer.
Wrap the connection with a bufio.Reader:
br := bufio.NewReader(conn)
Use the binary package to read an unsigned varint through the bufio.Reader:
n, err := binary. ReadUvarInt(br)
Because the bufio.Reader can buffer more than the varint, you should use the bufio.Reader for all subsequent reads on the connection.