Este documento descreve o protocolo binário para clientes TCP do ClickHouse.
Varint
Para comprimentos, códigos de pacote e outros casos, usa-se a codificação varint sem sinal. Use binary.PutUvarint e binary.ReadUvarint.
String
Strings de comprimento variável são codificadas como (comprimento, valor), em que comprimento é varint e valor é uma string UTF-8.
s := "Hello, world!"
// Escreve o comprimento da string como uvarint.
buf := make([]byte, binary.MaxVarintLen64)
n := binary.PutUvarint(buf, uint64(len(s)))
buf = buf[:n]
// Escreve o valor da string.
buf = append(buf, s...)r := bytes.NewReader([]byte{
0xd, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c,
0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21,
})
// Lê o comprimento.
n, err := binary.ReadUvarint(r)
if err != nil {
panic(err)
}
// Verifique n para evitar OOM ou exceção de runtime em make().
const maxSize = 1024 * 1024 * 10 // 10 MB
if n > maxSize || n < 0 {
panic("invalid n")
}
buf := make([]byte, n)
if _, err := io.ReadFull(r, buf); err != nil {
panic(err)
}
fmt.Println(string(buf))
// Hello, world!00000000 0d 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 |.Hello, world!|DUhlbGxvLCB3b3JsZCEdata := []byte{
0xd, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c,
0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21,
}Inteiros
Int32
v := int32(1000)
// Codificar.
buf := make([]byte, 8)
binary.LittleEndian.PutUint32(buf, uint32(v))
// Decodificar.
d := int32(binary.LittleEndian.Uint32(buf))
fmt.Println(d) // 100000000000 e8 03 00 00 00 00 00 00 |........|6AMAAAAAAAABooleano
Os valores booleanos são representados por um único byte: 1 é true e 0 é false.