Need some help with Go and Thrift

blov · · 529 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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(&#34;Error during Thrift serialization of type %s: %s&#34;, reflect.TypeOf(entity),err)) } else if (len(data) == 0) { panic(fmt.Sprintf(&#34;Error during Thrift serialization of type %s: %s&#34;, reflect.TypeOf(entity),&#34;0 bytes serialized!&#34;)) } 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(&#34;Error during Thrift serialization of type %s: %s&#34;, reflect.TypeOf(entity),&#34;0 bytes serialized!&#34;)) </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

529 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传