使用协议缓冲区发送二进制数据的正确方法是什么?
After using the protogen tool, I have a message type for sending messages:
type File struct {
Info string `protobuf:"bytes,1,opt,name=info,json=info" json:"info,omitempty"`
BytesValues []byte `protobuf:"bytes,2,opt,name=bytes_values,json=bytesValues,proto3" json:"bytes_values,omitempty"`
}
I am trying to send some binary data using the BytesValues
field like so:
filePath := filepath.Join("test", "myfile.bin")
f, _ := ioutil.ReadFile(filePath) // error return value ignored for brevity
msg := File{BytesValues: f}
body, _ := proto.Marshal(msg) // encode
The server seems to have problems decoding the message I am sending to it. Is this the correct way to send binary data using a []byte
field with protocol buffers?
使用了protogen工具后,我有一种消息类型用于发送消息: p>
我正在尝试发送一些二进制文件 使用 服务器似乎无法解码我发送给它的消息。 这是使用带有协议缓冲区的 type文件结构{
信息字符串`protobuf:“ bytes,1,opt,name = info,json = info” json:“ info,omitempty”`
BytesValues [] byte`protobuf:“ bytes ,2,opt,name = bytes_values,json = bytesValues,proto3“ json:” bytes_values,omitempty“`
}
code> pre>
BytesValues code>字段输入数据,如下所示: p>
filePath:= filepath.Join(“ test”,“ myfile.bin”)
f ,_:= ioutil.ReadFile(filePath)//为简洁起见忽略错误返回值
msg:= File {BytesValues:f}
body,_:= proto.Marshal(msg)//编码
pre>
[] byte code>字段发送二进制数据的正确方法吗? p>
div>
In my case, the problem was actually the server not reading the raw bytes from the correct field.
The correct way to send raw bytes is to just set the bytes to the field. There is no need to encode the bytes in any way because protocol buffers is a binary format.
filePath := filepath.Join("test", "myfile.bin")
f, _ := ioutil.ReadFile(filePath) // error return value ignored for brevity
msg := File{BytesValues: f}
body, _ := proto.Marshal(msg) // encode