繁体   English   中英

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

[英]how to parse a protobuf3 message without knowing its type at compile time with golang?

这是一个场景:

您正在golang中实现一个通用组件,该组件可以与任何类型的原型消息(二进制序列化)一起使用,并且需要在不知道编译类型的情况下反序列化二进制原型数据。

例如,我在编写通用的Kafka json归档文件时遇到了此问题,该组件将:

  • 从配置中接收消息类型(字符串)和kafka主题的名称
  • 将需要在运行时创建二进制->内存解串器和内存-> json序列化器。

如何仅从消息名称中获取二进制字节的反序列化器?

golang原型库具有用于此目的的帮助程序实用程序:

// 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 {
   // ....
}

要使用它,您可以使用与此类似的方法:

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
}

我在github上放了一个完整的例子: https : //github.com/rotemtam/pbreflect-example

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM