msgpack icon indicating copy to clipboard operation
msgpack copied to clipboard

Add custom unmarshaling support

Open merlinz01 opened this issue 1 year ago • 4 comments

This PR adds the capability to define an UnmarshalMsgpack() method on any type, which allows customizing how unmarshaling works.

The UnmarshalMsgpack() method takes a single parameter of type any which gets the value which would be unmarshaled into an any type. The method should check the type of the parameter, which can be any type that msgpack supports. The method returns the value to assign and any error encountered.

One use case for this is illustrated in the tests provided, where a string composed of concatenated IP networks is received and the user wants to parse them into a slice of net.IPNet's on the fly.

merlinz01 avatar Sep 14 '24 16:09 merlinz01

Hi.

Why don't you use ext format? Do you know how to use it? It seems like that we can encode the same as time.Time.

shamaton avatar Sep 19 '24 09:09 shamaton

I suppose I could do it that way. The ext.Encoder and ext.Decoder interfaces are not documented; could you show me how to use them?

merlinz01 avatar Sep 19 '24 16:09 merlinz01

Here is examples. https://github.com/shamaton/msgpack/blob/master/time/decode.go https://github.com/shamaton/msgpack/blob/master/time/encode.go

You implement your custom encoder and then call AddExtCoder when you start your service.

msgpack.AddExtCoder(encoder, decoder)

shamaton avatar Sep 23 '24 14:09 shamaton

Even the examples aren't documented. You need to add comments in the code to explain what's happening and what the function is for. I don't understand how I should make it decode my type.

merlinz01 avatar Sep 23 '24 17:09 merlinz01

Added comment in https://github.com/shamaton/msgpack/pull/48/commits/5fd37375532e3875ad440741cabb6d86bcc2bfce

shamaton avatar Aug 28 '25 23:08 shamaton