-
Notifications
You must be signed in to change notification settings - Fork 2
Tips and Tricks
Like encoding/json, msgp has a type called msgp.Raw that represents serialized MessagePack. You can use msgp.Raw for containers of arbitrary types and polymorphism. Take the following, for example:
type Data struct {
Header map[string]string
Body msgp.Raw
}The Data object could reasonably be used as a container for any MessagePack object. To de-serialize a concrete object from the raw data, you simply call (*msgp.Unmarshaler).UnmarshalMsg([]byte(Data.Body)).
Generating methods for a type defined outside the package in which you are currently working presents some challenges, as Go does not support defining methods for a type outside its originating package. There are some workarounds:
- You can specify
-srcin your//go:generatedirective to be a foreign file (located somewhere else in your GOPATH), for which code will be generated in the foreign package directly. Distributing such code would probably require maintaining a fork and/or git submodule. - You can define an identical
structtype in your own package and pointer-cast from the old type to the one defined in your package when you need to serialize. Better yet, create your own version with just the fields of the struct that you will be encoding or decoding.
All of the errors returned by the msgp package implement the msgp.Error interface. Thus, it is simple to distinguish between errors returned from encoding/decoding versus errors returned from other sources. Additionally, msgp errors will tell you whether or not the error allows the user to continue reading/writing to a stream. For example:
f, err := r.ReadFloat64()
if err != nil {
if msgerr, ok := err.(msgp.Error); ok && msgerr.Resumable() {
// the next object probably isn't a float64
}
// something else went wrong
log.Fatalln("something broke:", err)
}