<p>Hi fellow Gophers, newbie here trying to figure out how to serialize Thrift structs.</p>
<p>I am trying to write a generic method that can take any Thrift struct and serialize it to a byte array:</p>
<pre><code>func Go2Thrift(entity thrift.TStruct) []byte {
t := thrift.NewTSerializer()
transport := thrift.NewTMemoryBufferLen(1024)
defer transport.Close()
t.Protocol = thrift.NewTBinaryProtocolTransport(transport)
if data, err := t.Write(entity); err != nil {
panic(fmt.Sprintf("Error during Thrift serialization of type %s: %s", reflect.TypeOf(entity),err))
} else if (len(data) == 0) {
panic(fmt.Sprintf("Error during Thrift serialization of type %s: %s", reflect.TypeOf(entity),"0 bytes serialized!"))
} else {
return data
}
}
</code></pre>
<p>but no matter what I do, I get 0 bytes serialized hence this check kicks in:</p>
<pre><code> } else if (len(data) == 0) {
panic(fmt.Sprintf("Error during Thrift serialization of type %s: %s", reflect.TypeOf(entity),"0 bytes serialized!"))
</code></pre>
<p>I would appreciate if any one who has used Go and Thrift could help me figure out what I am doing wrong here.</p>
<p>I verified the input and it is a valid Thrift struct with all the fields set on it properly.</p>
<p>Thank you all in advance</p>
<hr/>**评论:**<br/><br/>tr0nical: <pre><p>I think what happens is that the t.Write() call will call entity.Write() with t.Protocol as argument. You initialized t.Protocol with your own buffer as buffer, so the bytes that t.Write() returns from t.Transport.Bytes() will be empty.</p>
<p>NewTSerializer() initializes the serialize by default to use a binary transport and a memory buffer, so I think you can simply get rid of the transport and protocol assignments and it should work.</p></pre>jfurmankiewicz: <pre><p>Thank you, yes that was it. Much appreciated.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传