使用协议缓冲区发送二进制数据的正确方法是什么?
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) // error return value ignored for brevity
msg := File{BytesValues: f}
body, _ := proto.Marshal(msg) // encode
服务器似乎无法解码我发送给它的消息。这是使用带有协议缓冲区的 []byte
字段发送二进制数据的正确方法吗?
在我的例子中,问题实际上是服务器没有从正确的字段读取原始字节。
发送原始字节的正确方法是将字节设置到字段中。不需要以任何方式对字节进行编码,因为协议缓冲区是二进制格式。
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
使用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) // error return value ignored for brevity
msg := File{BytesValues: f}
body, _ := proto.Marshal(msg) // encode
服务器似乎无法解码我发送给它的消息。这是使用带有协议缓冲区的 []byte
字段发送二进制数据的正确方法吗?
在我的例子中,问题实际上是服务器没有从正确的字段读取原始字节。
发送原始字节的正确方法是将字节设置到字段中。不需要以任何方式对字节进行编码,因为协议缓冲区是二进制格式。
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