Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

serialization - Go deserialization when type is not known

I'm writing a package in go to send messages between services, using a specific type of transport.

I'd like the package to not understand the type of messages being sent. My first thought is to serialize the message object into json, send that, deserialize on the receiving end, and pass the go object (as an interface{}) to the subscribing code.

The serialization isn't a problem, but I don't see how the generic package code can deserialize the message since it doesn't know the type. I thought of using reflect TypeOf(), and passing that value as part of the message. But I don't see how to accomplish this since Type is an interface and the implementing rtype is not exported.

If the receiving app gets an interface{}, it is going to have to check the type anyways, so maybe it should just do the deserialization. Or the receiver could provide a reflect Type so the package can deserialize?

Or it could give the receiver a map of field name to value, but I'd prefer the actual type.

Any suggestions?

Let me add an example:

I have a go channel for sending change notifications of different types of objects. Since go doesn't support tagged unions, I define the channel type as:

type UpdateInfo struct {
    UpdateType UpdateType
    OldObject interface{}
    NewObject interface{}
}

The receiving end of the channel gets an UpdateInfo with OldObject and NewObject as the actual concrete object types that were sent.

I want to extend this to work between applications, where the transport will be via a message queue to support pub/sub, multiple consumers, etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...