How to Use MessagePack in Go

Encode and decode Go structs to binary MessagePack format using the vmihailenco/msgpack library for efficient data serialization.

Use the github.com/vmihailenco/msgpack/v5 package to encode and decode Go structs into MessagePack binary format. Install the library, define your struct, then call msgpack.Marshal to serialize and msgpack.Unmarshal to deserialize data.

package main

import (
	"encoding/json"
	"fmt"
	"github.com/vmihailenco/msgpack/v5"
)

type User struct {
	ID   int
	Name string
}

func main() {
	user := User{ID: 1, Name: "Alice"}

	// Encode to MessagePack
	data, err := msgpack.Marshal(user)
	if err != nil {
		panic(err)
	}

	// Decode from MessagePack
	var decoded User
	err = msgpack.Unmarshal(data, &decoded)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Decoded: %+v\n", decoded)
}