How to convert bson.Binary to []byte in Go

huangapple go评论85阅读模式
英文:

How to convert bson.Binary to []byte in Go

问题

我正在编写一个小应用程序,它从网络接收以BSON格式编码的消息(不是来自MongoDB),并需要将字段保存到本地机器上的文件中。我正在使用gopkg.in/mgo.v2/bson来进行消息的解码,它工作得很好。

几乎一切都正常,除了一个问题。消息中有一个名为"userdefined"的二进制字段,我需要将其保存到单独的文件中。我尝试使用以下代码:

var pwr = msg["pwr"].([]byte)

但是出现了一个错误:"error panic: interface conversion: interface is bson.Binary, not []uint8"。

有人可以给我一个示例,说明如何将bson.Binary转换为[]byte,这样我就可以将其保存到文件中了。

英文:

I'm writing a small application that receives message in BSON format from network(its not MongoDB) and have to save fields in files on local machine. I'm using gopkg.in/mgo.v2/bson for message unmarshaling and it works fine.

Almost everything works except one. There "userdefined" binary field in message and I have to save it to separate file. I tried to use:

var pwr = msg["pwr"].([]byte)

but got an "error panic: interface conversion: interface is bson.Binary, not []uint8".

Can some one point me an example how to convert bson.Binary to []byte, so I can save it to file.

答案1

得分: 0

这是你想要的效果:

pwr := bson.Binary(msg["pwr"].(bson.Binary)).Data

但是假设 msg["pwr"] 只能是 bson.Binary 类型... 如果这不是一个不变量,你应该先进行类型断言(处理可能的类型不匹配情况),然后再进行转换以获取 Data 字段。

英文:

This does what you want:

pwr := bson.Binary(msg["pwr"].(bson.Binary)).Data

But assumes msg["pwr"] can't be anything other than a bson.Binary... if that's not an invariant you should do the type assertion first (handle the possible type mismatch case when it happens) and then cast to get the Data field.

huangapple
  • 本文由 发表于 2017年1月12日 22:47:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/41616043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定