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

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

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试