Parse Kafka.header to int in go lang

822 Views Asked by At

I have been trying to convert []kafka.Header to int in Go. I have tried quite a few approaches so far.

A few of them are:

  • converting the byte array to string and then to int - string(header.Value)
  • converting the first byte to string and then to int - string(header.Value[0])
  • converting the first byte to int - int(header.Value[0])
  • converting the byte array to int using strconv - strconv.Atoi(string(header.Value))
  • custom function to parse by using the base 10 and base 16

But all the approaches so far have either resulted in an error or incorrect conversion.

Snapshot of error messages:

  • err: strconv.Atoi: parsing "\x01\x00\x00\x00": invalid syntax
  • encoding/hex: invalid byte: U+0001

The input is something like this (single hex bytes in ASCII) - headers: [requestNum="\x01\x00\x00\x00" retryNum="\x1c\x00\x00\x00" retryDelaySecs="@\x01\x00\x00"]

The expected output is their int equivalents i.e. 1, 28, 320

Feel free to ask for more info. Please assist me with the same with any suggestions. Thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

Use the encoding/binary package to read binary data. For example:

package main

import (
    "encoding/binary"
    "fmt"

    "github.com/confluentinc/confluent-kafka-go/kafka"
)

func main() {
    headers := []kafka.Header{
        {
            Key:   "requestNum",
            Value: []byte("\x01\x00\x00\x00"),
        },
        {
            Key:   "retryNum",
            Value: []byte("\x1c\x00\x00\x00"),
        },
        {
            Key:   "retryDelaySecs",
            Value: []byte("@\x01\x00\x00"),
        },
    }

    for _, h := range headers {
        v := binary.LittleEndian.Uint32(h.Value)
        fmt.Printf("%s: %d\n", h.Key, v)
    }
}