質問

I have a golang based client that must to speak with a C daemon, using a binary protocol. I cannot change the server, to support json, xml or other protocol.

in the C code, i have to fill in the following struct and send it via network:

typedef struct pkt_struct{
    int16_t   pkt_version;
    int16_t   pkt_type;
    u_int32_t crc32_v;
    int16_t   ret_code;
    char      buffer[1024];
}pkt;

to have an idea, how do I need the data, it should look like the output from:

$ irb
2.0.0-p353 :002 > [2, 1, 0, 0, 'version', 3].pack("nnNna1024n")

is gob the answer? reading through the documentation, looks that it is not. maybe ProtoBuf?

what I did until now is:

import "encoding/binary"

....
type NPacket struct {
    packet_version int16
    packet_type int16
    crc32_value uint32
    ret_code int16
    buffer string
 }
 ....
 var pkt_send NPacket
 pkt_send = NPacket{2,1,0,0,"version"}
 buf := new(bytes.Buffer)
 if err := binary.Write(buf, binary.BigEndian, &pkt_send); err != nil {
        fmt.Println(err)
        os.Exit(1)
 }

error that I'm getting:

binary.Write: invalid type string
役に立ちましたか?

解決

binary.Write only works on fixed sized objects. A string may be any size. Instead, you probably want to copy your C code and use a fixed size byte array:

type NPacket struct {
    packet_version int16
    packet_type int16
    crc32_value uint32
    ret_code int16
    buffer [1024]byte
}

You can set the buffer with copy(pkt.buffer[:], "string").


Neither gob nor protobufs are the answer. They are both encoding formats and give you no control over how the data is marshalled.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top