How do I encode a struct to/from MessagePack in Go?

In Go, you can encode and decode structs to/from MessagePack using the `github.com/vmihailenco/msgpack` package. This package provides easy serialization and deserialization of Go data structures into the MessagePack format, which is efficient for both size and speed.

Example Usage

Below is an example of how to encode and decode a struct using MessagePack in Go:

package main import ( "bytes" "fmt" "github.com/vmihailenco/msgpack/v5" ) // Define a struct type Person struct { Name string `msgpack:"name"` Age int `msgpack:"age"` } func main() { // Create an instance of the struct person := Person{Name: "Alice", Age: 30} // Encode the struct to MessagePack var buf bytes.Buffer encoder := msgpack.NewEncoder(&buf) err := encoder.Encode(person) if err != nil { fmt.Println("Encode error:", err) return } // Decode the struct from MessagePack var decodedPerson Person decoder := msgpack.NewDecoder(&buf) err = decoder.Decode(&decodedPerson) if err != nil { fmt.Println("Decode error:", err) return } // Display the result fmt.Printf("Decoded Person: %+v\n", decodedPerson) }

Go MessagePack Go encoding Go decoding Go struct serialization