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

如何在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

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化