英文:
What is the correct way to send binary data using protocol buffers?
问题
使用protogen工具后,我有一个用于发送消息的消息类型:
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"`
}
我试图使用BytesValues
字段发送一些二进制数据,像这样:
filePath := filepath.Join("test", "myfile.bin")
f, _ := ioutil.ReadFile(filePath) // 忽略错误返回值以简洁表示
msg := File{BytesValues: f}
body, _ := proto.Marshal(msg) // 编码
服务器似乎无法解码我发送的消息。这是使用协议缓冲区发送二进制数据的正确方法吗?
英文:
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?
答案1
得分: 0
在我的情况下,问题实际上是服务器没有从正确的字段读取原始字节。
发送原始字节的正确方法是将字节设置为字段的值。没有必要以任何方式对字节进行编码,因为协议缓冲区是一种二进制格式。
filePath := filepath.Join("test", "myfile.bin")
f, _ := ioutil.ReadFile(filePath) // 忽略错误返回值以简洁为目的
msg := File{BytesValues: f}
body, _ := proto.Marshal(msg) // 编码
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论