簡體   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