這是一個場景:您正在 golang 中實現一個通用組件,它可以與任何類型的原型消息(二進制序列化)一起使用,并且需要在編譯時不知道其類型的情況下反序列化二進制原型數據。例如,我在編寫通用的 kafka json 歸檔程序時遇到了這個問題,該組件將:從配置中接收消息類型(字符串)和 kafka 主題的名稱需要在運行時創建二進制 -> 內存解串器和內存 -> json 序列化器。你如何從消息名稱中獲得二進制字節的反序列化器?
1 回答

料青山看我應如是
TA貢獻1772條經驗 獲得超8個贊
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
}
- 1 回答
- 0 關注
- 165 瀏覽