duanbinren8906 2018-12-29 11:07
浏览 255
已采纳

如何在golang编译时不知道protobuf3消息类型的情况下解析它?

here's a scenario:

you're implementing in golang a generic component that can may be used with any type of proto message (binary serialization) and need to deserialize binary proto data without knowing its type at compile time.

for instance, i encountered this issue while writing a generic kafka json archiver, the component would:

  • receive a message type (string) from configuration and a name of a kafka topic
  • would need to create the binary -> memory deserializer and the memory -> json serializer at runtime.

how do you get a deserializer for your binary bytes just from the message name?

  • 写回答

1条回答 默认 最新

  • dousu8456 2018-12-29 11:07
    关注

    golang proto libraries have a helper utility for this purpose:

    // MessageType returns the message type (pointer to struct) for a named message.
    // The type is not guaranteed to implement proto.Message if the name refers to a
    // map entry.
    func MessageType(name string) reflect.Type {
       // ....
    }
    

    to use it you can use a method similar to this:

    func getProto(messageType string, messageBytes []byte) proto.Message {
        pbtype := proto.MessageType(messageType)
        msg := reflect.New(pbtype.Elem()).Interface().(proto.Message)
        proto.Unmarshal(messageBytes, msg)
        return msg
    }
    

    i have put a full example of this on github: https://github.com/rotemtam/pbreflect-example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度