goapache-kafkaconfluent-kafka-go

Parse Kafka.header to int in go lang


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:

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

Snapshot of error messages:

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.


Solution

  • 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)
        }
    }