🌐 US-Proxy
>

msgpack

package module
v5.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2023 License: BSD-2-Clause Imports: 18 Imported by: 1,833

README ΒΆ

MessagePack encoding for Golang

Build Status PkgGoDev Documentation Chat

msgpack is brought to you by ⭐ uptrace/uptrace. Uptrace is an open source APM and blazingly fast distributed tracing tool powered by OpenTelemetry and ClickHouse. Give it a star as well!

Resources

Features

Installation

msgpack supports 2 last Go versions and requires support for Go modules. So make sure to initialize a Go module:

go mod init github.com/my/repo

And then install msgpack/v5 (note v5 in the import; omitting it is a popular mistake):

go get github.com/vmihailenco/msgpack/v5

Quickstart

import "github.com/vmihailenco/msgpack/v5"

func ExampleMarshal() {
    type Item struct {
        Foo string
    }

    b, err := msgpack.Marshal(&Item{Foo: "bar"})
    if err != nil {
        panic(err)
    }

    var item Item
    err = msgpack.Unmarshal(b, &item)
    if err != nil {
        panic(err)
    }
    fmt.Println(item.Foo)
    // Output: bar
}

See also

Contributors

Thanks to all the people who already contributed!

Documentation ΒΆ

Index ΒΆ

Examples ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func Marshal ΒΆ

func Marshal(v interface{}) ([]byte, error)

Marshal returns the MessagePack encoding of v.

Example ΒΆ
package main

import (
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

func main() {
	type Item struct {
		Foo string
	}

	b, err := msgpack.Marshal(&Item{Foo: "bar"})
	if err != nil {
		panic(err)
	}

	var item Item
	err = msgpack.Unmarshal(b, &item)
	if err != nil {
		panic(err)
	}
	fmt.Println(item.Foo)
}
Output:
bar
Example (AsArray) ΒΆ
package main

import (
	"bytes"
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

func main() {
	type Item struct {
		_msgpack struct{} `msgpack:",as_array"`
		Foo      string
		Bar      string
	}

	var buf bytes.Buffer
	enc := msgpack.NewEncoder(&buf)
	err := enc.Encode(&Item{Foo: "foo", Bar: "bar"})
	if err != nil {
		panic(err)
	}

	dec := msgpack.NewDecoder(&buf)
	v, err := dec.DecodeInterface()
	if err != nil {
		panic(err)
	}
	fmt.Println(v)
}
Output:
[foo bar]
Example (EscapedNames) ΒΆ
package main

import (
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

func main() {
	og := map[string]interface{}{
		"something:special": uint(123),
		"hello, world":      "hello!",
	}
	raw, err := msgpack.Marshal(og)
	if err != nil {
		panic(err)
	}

	type Item struct {
		SomethingSpecial uint   `msgpack:"'something:special'"`
		HelloWorld       string `msgpack:"'hello, world'"`
	}
	var item Item
	if err := msgpack.Unmarshal(raw, &item); err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", item)
}
Output:
msgpack_test.Item{SomethingSpecial:0x7b, HelloWorld:"hello!"}
Example (Ignore_simple_zero_structs_when_tagged_with_omitempty) ΒΆ
package main

import (
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

type NullInt struct {
	Valid bool
	Int   int
}

func (i *NullInt) Set(j int) {
	i.Int = j
	i.Valid = true
}

func (i NullInt) IsZero() bool {
	return !i.Valid
}

func (i NullInt) MarshalMsgpack() ([]byte, error) {
	return msgpack.Marshal(i.Int)
}

func (i *NullInt) UnmarshalMsgpack(b []byte) error {
	if err := msgpack.Unmarshal(b, &i.Int); err != nil {
		return err
	}
	i.Valid = true
	return nil
}

type Secretive struct {
	Visible bool
	hidden  bool
}

type T struct {
	I NullInt `msgpack:",omitempty"`
	J NullInt

	S Secretive `msgpack:",omitempty"`
}

func main() {
	var t1 T
	raw, err := msgpack.Marshal(t1)
	if err != nil {
		panic(err)
	}
	var t2 T
	if err = msgpack.Unmarshal(raw, &t2); err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", t2)

	t2.I.Set(42)
	t2.S.hidden = true // won't be included because it is a hidden field
	raw, err = msgpack.Marshal(t2)
	if err != nil {
		panic(err)
	}
	var t3 T
	if err = msgpack.Unmarshal(raw, &t3); err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", t3)
}
Output:
msgpack_test.T{I:msgpack_test.NullInt{Valid:false, Int:0}, J:msgpack_test.NullInt{Valid:true, Int:0}, S:msgpack_test.Secretive{Visible:false, hidden:false}}
msgpack_test.T{I:msgpack_test.NullInt{Valid:true, Int:42}, J:msgpack_test.NullInt{Valid:true, Int:0}, S:msgpack_test.Secretive{Visible:false, hidden:false}}
Example (MapStringInterface) ΒΆ
package main

import (
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

func main() {
	in := map[string]interface{}{"foo": 1, "hello": "world"}
	b, err := msgpack.Marshal(in)
	if err != nil {
		panic(err)
	}

	var out map[string]interface{}
	err = msgpack.Unmarshal(b, &out)
	if err != nil {
		panic(err)
	}

	fmt.Println("foo =", out["foo"])
	fmt.Println("hello =", out["hello"])

}
Output:
foo = 1
hello = world
Example (OmitEmpty) ΒΆ
package main

import (
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

func main() {
	type Item struct {
		Foo string
		Bar string
	}

	item := &Item{
		Foo: "hello",
	}
	b, err := msgpack.Marshal(item)
	if err != nil {
		panic(err)
	}
	fmt.Printf("item: %q\n", b)

	type ItemOmitEmpty struct {
		_msgpack struct{} `msgpack:",omitempty"`
		Foo      string
		Bar      string
	}

	itemOmitEmpty := &ItemOmitEmpty{
		Foo: "hello",
	}
	b, err = msgpack.Marshal(itemOmitEmpty)
	if err != nil {
		panic(err)
	}
	fmt.Printf("item2: %q\n", b)

}
Output:
item: "\x82\xa3Foo\xa5hello\xa3Bar\xa0"
item2: "\x81\xa3Foo\xa5hello"

func PutDecoder ΒΆ

func PutDecoder(dec *Decoder)

func PutEncoder ΒΆ

func PutEncoder(enc *Encoder)

func Register ΒΆ

func Register(value interface{}, enc encoderFunc, dec decoderFunc)

Register registers encoder and decoder functions for a value. This is low level API and in most cases you should prefer implementing CustomEncoder/CustomDecoder or Marshaler/Unmarshaler interfaces.

func RegisterExt ΒΆ

func RegisterExt(extID int8, value MarshalerUnmarshaler)
Example ΒΆ
package main

import (
	"encoding/binary"
	"fmt"
	"time"

	"github.com/vmihailenco/msgpack/v5"
)

// https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1#eventtime-ext-format
type EventTime struct {
	time.Time
}

type OneMoreSecondEventTime struct {
	EventTime
}

func (tm *EventTime) MarshalMsgpack() ([]byte, error) {
	b := make([]byte, 8)
	binary.BigEndian.PutUint32(b, uint32(tm.Unix()))
	binary.BigEndian.PutUint32(b[4:], uint32(tm.Nanosecond()))
	return b, nil
}

func (tm *EventTime) UnmarshalMsgpack(b []byte) error {
	if len(b) != 8 {
		return fmt.Errorf("invalid data length: got %d, wanted 8", len(b))
	}
	sec := binary.BigEndian.Uint32(b)
	usec := binary.BigEndian.Uint32(b[4:])
	tm.Time = time.Unix(int64(sec), int64(usec))
	return nil
}

func (tm *OneMoreSecondEventTime) MarshalMsgpack() ([]byte, error) {
	b := make([]byte, 8)
	binary.BigEndian.PutUint32(b, uint32(tm.Unix()+1))
	binary.BigEndian.PutUint32(b[4:], uint32(tm.Nanosecond()))
	return b, nil
}

func (tm *OneMoreSecondEventTime) UnmarshalMsgpack(b []byte) error {
	if len(b) != 8 {
		return fmt.Errorf("invalid data length: got %d, wanted 8", len(b))
	}
	sec := binary.BigEndian.Uint32(b)
	usec := binary.BigEndian.Uint32(b[4:])
	tm.Time = time.Unix(int64(sec+1), int64(usec))
	return nil
}

func main() {
	t := time.Unix(123456789, 123)

	{
		msgpack.RegisterExt(1, (*EventTime)(nil))
		b, err := msgpack.Marshal(&EventTime{t})
		if err != nil {
			panic(err)
		}

		var v interface{}
		err = msgpack.Unmarshal(b, &v)
		if err != nil {
			panic(err)
		}
		fmt.Println(v.(*EventTime).UTC())

		tm := new(EventTime)
		err = msgpack.Unmarshal(b, &tm)
		if err != nil {
			panic(err)
		}
		fmt.Println(tm.UTC())
	}

	{
		msgpack.RegisterExt(1, (*EventTime)(nil))
		b, err := msgpack.Marshal(&EventTime{t})
		if err != nil {
			panic(err)
		}

		// override ext
		msgpack.RegisterExt(1, (*OneMoreSecondEventTime)(nil))

		var v interface{}
		err = msgpack.Unmarshal(b, &v)
		if err != nil {
			panic(err)
		}
		fmt.Println(v.(*OneMoreSecondEventTime).UTC())
	}

	{
		msgpack.RegisterExt(1, (*OneMoreSecondEventTime)(nil))
		b, err := msgpack.Marshal(&OneMoreSecondEventTime{
			EventTime{t},
		})
		if err != nil {
			panic(err)
		}

		// override ext
		msgpack.RegisterExt(1, (*EventTime)(nil))
		var v interface{}
		err = msgpack.Unmarshal(b, &v)
		if err != nil {
			panic(err)
		}
		fmt.Println(v.(*EventTime).UTC())
	}

}
Output:
1973-11-29 21:33:09.000000123 +0000 UTC
1973-11-29 21:33:09.000000123 +0000 UTC
1973-11-29 21:33:10.000000123 +0000 UTC
1973-11-29 21:33:10.000000123 +0000 UTC

func RegisterExtDecoder ΒΆ

func RegisterExtDecoder(
	extID int8,
	value interface{},
	decoder func(dec *Decoder, v reflect.Value, extLen int) error,
)

func RegisterExtEncoder ΒΆ

func RegisterExtEncoder(
	extID int8,
	value interface{},
	encoder func(enc *Encoder, v reflect.Value) ([]byte, error),
)

func Unmarshal ΒΆ

func Unmarshal(data []byte, v interface{}) error

Unmarshal decodes the MessagePack-encoded data and stores the result in the value pointed to by v.

func UnregisterExt ΒΆ added in v5.1.0

func UnregisterExt(extID int8)
Example ΒΆ
package main

import (
	"encoding/binary"
	"fmt"
	"time"

	"github.com/vmihailenco/msgpack/v5"
)

// https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1#eventtime-ext-format
type EventTime struct {
	time.Time
}

type OneMoreSecondEventTime struct {
	EventTime
}

func (tm *EventTime) MarshalMsgpack() ([]byte, error) {
	b := make([]byte, 8)
	binary.BigEndian.PutUint32(b, uint32(tm.Unix()))
	binary.BigEndian.PutUint32(b[4:], uint32(tm.Nanosecond()))
	return b, nil
}

func (tm *EventTime) UnmarshalMsgpack(b []byte) error {
	if len(b) != 8 {
		return fmt.Errorf("invalid data length: got %d, wanted 8", len(b))
	}
	sec := binary.BigEndian.Uint32(b)
	usec := binary.BigEndian.Uint32(b[4:])
	tm.Time = time.Unix(int64(sec), int64(usec))
	return nil
}

func (tm *OneMoreSecondEventTime) MarshalMsgpack() ([]byte, error) {
	b := make([]byte, 8)
	binary.BigEndian.PutUint32(b, uint32(tm.Unix()+1))
	binary.BigEndian.PutUint32(b[4:], uint32(tm.Nanosecond()))
	return b, nil
}

func (tm *OneMoreSecondEventTime) UnmarshalMsgpack(b []byte) error {
	if len(b) != 8 {
		return fmt.Errorf("invalid data length: got %d, wanted 8", len(b))
	}
	sec := binary.BigEndian.Uint32(b)
	usec := binary.BigEndian.Uint32(b[4:])
	tm.Time = time.Unix(int64(sec+1), int64(usec))
	return nil
}

func main() {
	t := time.Unix(123456789, 123)

	{
		msgpack.RegisterExt(1, (*EventTime)(nil))
		b, err := msgpack.Marshal(&EventTime{t})
		if err != nil {
			panic(err)
		}

		msgpack.UnregisterExt(1)

		var v interface{}
		err = msgpack.Unmarshal(b, &v)
		wanted := "msgpack: unknown ext id=1"
		if err.Error() != wanted {
			panic(err)
		}

		msgpack.RegisterExt(1, (*OneMoreSecondEventTime)(nil))
		err = msgpack.Unmarshal(b, &v)
		if err != nil {
			panic(err)
		}
		fmt.Println(v.(*OneMoreSecondEventTime).UTC())
	}

	{
		msgpack.RegisterExt(1, (*OneMoreSecondEventTime)(nil))
		b, err := msgpack.Marshal(&OneMoreSecondEventTime{
			EventTime{t},
		})
		if err != nil {
			panic(err)
		}

		msgpack.UnregisterExt(1)
		var v interface{}
		err = msgpack.Unmarshal(b, &v)
		wanted := "msgpack: unknown ext id=1"
		if err.Error() != wanted {
			panic(err)
		}

		msgpack.RegisterExt(1, (*EventTime)(nil))
		err = msgpack.Unmarshal(b, &v)
		if err != nil {
			panic(err)
		}
		fmt.Println(v.(*EventTime).UTC())
	}

}
Output:
1973-11-29 21:33:10.000000123 +0000 UTC
1973-11-29 21:33:10.000000123 +0000 UTC

func Version ΒΆ added in v5.3.5

func Version() string

Version is the current release version.

Types ΒΆ

type CustomDecoder ΒΆ

type CustomDecoder interface {
	DecodeMsgpack(*Decoder) error
}

type CustomEncoder ΒΆ

type CustomEncoder interface {
	EncodeMsgpack(*Encoder) error
}
Example ΒΆ
package main

import (
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

type customStruct struct {
	S string
	N int
}

var _ msgpack.CustomEncoder = (*customStruct)(nil)
var _ msgpack.CustomDecoder = (*customStruct)(nil)

func (s *customStruct) EncodeMsgpack(enc *msgpack.Encoder) error {
	return enc.EncodeMulti(s.S, s.N)
}

func (s *customStruct) DecodeMsgpack(dec *msgpack.Decoder) error {
	return dec.DecodeMulti(&s.S, &s.N)
}

func main() {
	b, err := msgpack.Marshal(&customStruct{S: "hello", N: 42})
	if err != nil {
		panic(err)
	}

	var v customStruct
	err = msgpack.Unmarshal(b, &v)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%#v", v)
}
Output:
msgpack_test.customStruct{S:"hello", N:42}

type Decoder ΒΆ

type Decoder struct {
	// contains filtered or unexported fields
}

A Decoder reads and decodes MessagePack values from an input stream.

func GetDecoder ΒΆ

func GetDecoder() *Decoder

func NewDecoder ΒΆ

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from r.

The decoder introduces its own buffering and may read data from r beyond the requested msgpack values. Buffering can be disabled by passing a reader that implements io.ByteScanner interface.

func (*Decoder) Buffered ΒΆ

func (d *Decoder) Buffered() io.Reader

Buffered returns a reader of the data remaining in the Decoder's buffer. The reader is valid until the next call to Decode.

func (*Decoder) Decode ΒΆ

func (d *Decoder) Decode(v interface{}) error

func (*Decoder) DecodeArrayLen ΒΆ

func (d *Decoder) DecodeArrayLen() (int, error)

DecodeArrayLen decodes array length. Length is -1 when array is nil.

func (*Decoder) DecodeBool ΒΆ

func (d *Decoder) DecodeBool() (bool, error)

func (*Decoder) DecodeBytes ΒΆ

func (d *Decoder) DecodeBytes() ([]byte, error)

func (*Decoder) DecodeBytesLen ΒΆ

func (d *Decoder) DecodeBytesLen() (int, error)

func (*Decoder) DecodeDuration ΒΆ

func (d *Decoder) DecodeDuration() (time.Duration, error)

func (*Decoder) DecodeExtHeader ΒΆ

func (d *Decoder) DecodeExtHeader() (extID int8, extLen int, err error)

func (*Decoder) DecodeFloat32 ΒΆ

func (d *Decoder) DecodeFloat32() (float32, error)

func (*Decoder) DecodeFloat64 ΒΆ

func (d *Decoder) DecodeFloat64() (float64, error)

DecodeFloat64 decodes msgpack float32/64 into Go float64.

func (*Decoder) DecodeInt ΒΆ

func (d *Decoder) DecodeInt() (int, error)

func (*Decoder) DecodeInt8 ΒΆ

func (d *Decoder) DecodeInt8() (int8, error)

func (*Decoder) DecodeInt16 ΒΆ

func (d *Decoder) DecodeInt16() (int16, error)

func (*Decoder) DecodeInt32 ΒΆ

func (d *Decoder) DecodeInt32() (int32, error)

func (*Decoder) DecodeInt64 ΒΆ

func (d *Decoder) DecodeInt64() (int64, error)

DecodeInt64 decodes msgpack int8/16/32/64 and uint8/16/32/64 into Go int64.

func (*Decoder) DecodeInterface ΒΆ

func (d *Decoder) DecodeInterface() (interface{}, error)

DecodeInterface decodes value into interface. It returns following types:

  • nil,
  • bool,
  • int8, int16, int32, int64,
  • uint8, uint16, uint32, uint64,
  • float32 and float64,
  • string,
  • []byte,
  • slices of any of the above,
  • maps of any of the above.

DecodeInterface should be used only when you don't know the type of value you are decoding. For example, if you are decoding number it is better to use DecodeInt64 for negative numbers and DecodeUint64 for positive numbers.

func (*Decoder) DecodeInterfaceLoose ΒΆ

func (d *Decoder) DecodeInterfaceLoose() (interface{}, error)

DecodeInterfaceLoose is like DecodeInterface except that:

  • int8, int16, and int32 are converted to int64,
  • uint8, uint16, and uint32 are converted to uint64,
  • float32 is converted to float64.
  • []byte is converted to string.

func (*Decoder) DecodeMap ΒΆ

func (d *Decoder) DecodeMap() (map[string]interface{}, error)

func (*Decoder) DecodeMapLen ΒΆ

func (d *Decoder) DecodeMapLen() (int, error)

DecodeMapLen decodes map length. Length is -1 when map is nil.

func (*Decoder) DecodeMulti ΒΆ

func (d *Decoder) DecodeMulti(v ...interface{}) error

func (*Decoder) DecodeNil ΒΆ

func (d *Decoder) DecodeNil() error

func (*Decoder) DecodeRaw ΒΆ

func (d *Decoder) DecodeRaw() (RawMessage, error)

func (*Decoder) DecodeSlice ΒΆ

func (d *Decoder) DecodeSlice() ([]interface{}, error)

func (*Decoder) DecodeString ΒΆ

func (d *Decoder) DecodeString() (string, error)

func (*Decoder) DecodeTime ΒΆ

func (d *Decoder) DecodeTime() (time.Time, error)

func (*Decoder) DecodeTypedMap ΒΆ

func (d *Decoder) DecodeTypedMap() (interface{}, error)

DecodeTypedMap decodes a typed map. Typed map is a map that has a fixed type for keys and values. Key and value types may be different.

func (*Decoder) DecodeUint ΒΆ

func (d *Decoder) DecodeUint() (uint, error)

func (*Decoder) DecodeUint8 ΒΆ

func (d *Decoder) DecodeUint8() (uint8, error)

func (*Decoder) DecodeUint16 ΒΆ

func (d *Decoder) DecodeUint16() (uint16, error)

func (*Decoder) DecodeUint32 ΒΆ

func (d *Decoder) DecodeUint32() (uint32, error)

func (*Decoder) DecodeUint64 ΒΆ

func (d *Decoder) DecodeUint64() (uint64, error)

DecodeUint64 decodes msgpack int8/16/32/64 and uint8/16/32/64 into Go uint64.

func (*Decoder) DecodeUntypedMap ΒΆ

func (d *Decoder) DecodeUntypedMap() (map[interface{}]interface{}, error)

func (*Decoder) DecodeValue ΒΆ

func (d *Decoder) DecodeValue(v reflect.Value) error

func (*Decoder) DisableAllocLimit ΒΆ added in v5.4.0

func (d *Decoder) DisableAllocLimit(on bool)

DisableAllocLimit enables fully allocating slices/maps when the size is known

func (*Decoder) DisallowUnknownFields ΒΆ

func (d *Decoder) DisallowUnknownFields(on bool)

DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

func (*Decoder) PeekCode ΒΆ

func (d *Decoder) PeekCode() (byte, error)

PeekCode returns the next MessagePack code without advancing the reader. Subpackage msgpack/codes defines the list of available msgpcode.

func (*Decoder) Query ΒΆ

func (d *Decoder) Query(query string) ([]interface{}, error)

Query extracts data specified by the query from the msgpack stream skipping any other data. Query consists of map keys and array indexes separated with dot, e.g. key1.0.key2.

Example ΒΆ
package main

import (
	"bytes"
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

func main() {
	b, err := msgpack.Marshal([]map[string]interface{}{
		{"id": 1, "attrs": map[string]interface{}{"phone": 12345}},
		{"id": 2, "attrs": map[string]interface{}{"phone": 54321}},
	})
	if err != nil {
		panic(err)
	}

	dec := msgpack.NewDecoder(bytes.NewBuffer(b))
	values, err := dec.Query("*.attrs.phone")
	if err != nil {
		panic(err)
	}
	fmt.Println("phones are", values)

	dec.Reset(bytes.NewBuffer(b))
	values, err = dec.Query("1.attrs.phone")
	if err != nil {
		panic(err)
	}
	fmt.Println("2nd phone is", values[0])
}
Output:
phones are [12345 54321]
2nd phone is 54321

func (*Decoder) ReadFull ΒΆ

func (d *Decoder) ReadFull(buf []byte) error

ReadFull reads exactly len(buf) bytes into the buf.

func (*Decoder) Reset ΒΆ

func (d *Decoder) Reset(r io.Reader)

Reset discards any buffered data, resets all state, and switches the buffered reader to read from r.

func (*Decoder) ResetDict ΒΆ

func (d *Decoder) ResetDict(r io.Reader, dict []string)

ResetDict is like Reset, but also resets the dict.

func (*Decoder) ResetReader ΒΆ added in v5.4.0

func (d *Decoder) ResetReader(r io.Reader)

func (*Decoder) SetCustomStructTag ΒΆ

func (d *Decoder) SetCustomStructTag(tag string)

SetCustomStructTag causes the decoder to use the supplied tag as a fallback option if there is no msgpack tag.

func (*Decoder) SetMapDecoder ΒΆ

func (d *Decoder) SetMapDecoder(fn func(*Decoder) (interface{}, error))
Example ΒΆ
package main

import (
	"bytes"
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

func main() {
	buf := new(bytes.Buffer)

	enc := msgpack.NewEncoder(buf)
	in := map[string]string{"hello": "world"}
	err := enc.Encode(in)
	if err != nil {
		panic(err)
	}

	dec := msgpack.NewDecoder(buf)

	// Causes decoder to produce map[string]string instead of map[string]interface{}.
	dec.SetMapDecoder(func(d *msgpack.Decoder) (interface{}, error) {
		n, err := d.DecodeMapLen()
		if err != nil {
			return nil, err
		}

		m := make(map[string]string, n)
		for i := 0; i < n; i++ {
			mk, err := d.DecodeString()
			if err != nil {
				return nil, err
			}

			mv, err := d.DecodeString()
			if err != nil {
				return nil, err
			}

			m[mk] = mv
		}
		return m, nil
	})

	out, err := dec.DecodeInterface()
	if err != nil {
		panic(err)
	}
	fmt.Printf("%#v", out)
}
Output:
map[string]string{"hello":"world"}

func (*Decoder) Skip ΒΆ

func (d *Decoder) Skip() error

Skip skips next value.

func (*Decoder) UseInternedStrings ΒΆ

func (d *Decoder) UseInternedStrings(on bool)

UseInternedStrings enables support for decoding interned strings.

func (*Decoder) UseLooseInterfaceDecoding ΒΆ

func (d *Decoder) UseLooseInterfaceDecoding(on bool)

UseLooseInterfaceDecoding causes decoder to use DecodeInterfaceLoose to decode msgpack value into Go interface{}.

func (*Decoder) UsePreallocateValues ΒΆ added in v5.4.0

func (d *Decoder) UsePreallocateValues(on bool)

UsePreallocateValues enables preallocating values in chunks

func (*Decoder) WithDict ΒΆ added in v5.1.3

func (d *Decoder) WithDict(dict []string, fn func(*Decoder) error) error

type Encoder ΒΆ

type Encoder struct {
	// contains filtered or unexported fields
}

func GetEncoder ΒΆ

func GetEncoder() *Encoder

func NewEncoder ΒΆ

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

func (*Encoder) Encode ΒΆ

func (e *Encoder) Encode(v interface{}) error

func (*Encoder) EncodeArrayLen ΒΆ

func (e *Encoder) EncodeArrayLen(l int) error

func (*Encoder) EncodeBool ΒΆ

func (e *Encoder) EncodeBool(value bool) error

func (*Encoder) EncodeBytes ΒΆ

func (e *Encoder) EncodeBytes(v []byte) error

func (*Encoder) EncodeBytesLen ΒΆ

func (e *Encoder) EncodeBytesLen(l int) error

func (*Encoder) EncodeDuration ΒΆ

func (e *Encoder) EncodeDuration(d time.Duration) error

func (*Encoder) EncodeExtHeader ΒΆ

func (e *Encoder) EncodeExtHeader(extID int8, extLen int) error

func (*Encoder) EncodeFloat32 ΒΆ

func (e *Encoder) EncodeFloat32(n float32) error

func (*Encoder) EncodeFloat64 ΒΆ

func (e *Encoder) EncodeFloat64(n float64) error

func (*Encoder) EncodeInt ΒΆ

func (e *Encoder) EncodeInt(n int64) error

EncodeNumber encodes an int64 in 1, 2, 3, 5, or 9 bytes. Type of the number is lost during encoding.

func (*Encoder) EncodeInt8 ΒΆ

func (e *Encoder) EncodeInt8(n int8) error

EncodeInt8 encodes an int8 in 2 bytes preserving type of the number.

func (*Encoder) EncodeInt16 ΒΆ

func (e *Encoder) EncodeInt16(n int16) error

EncodeInt16 encodes an int16 in 3 bytes preserving type of the number.

func (*Encoder) EncodeInt32 ΒΆ

func (e *Encoder) EncodeInt32(n int32) error

EncodeInt32 encodes an int32 in 5 bytes preserving type of the number.

func (*Encoder) EncodeInt64 ΒΆ

func (e *Encoder) EncodeInt64(n int64) error

EncodeInt64 encodes an int64 in 9 bytes preserving type of the number.

func (*Encoder) EncodeMap ΒΆ

func (e *Encoder) EncodeMap(m map[string]interface{}) error

func (*Encoder) EncodeMapLen ΒΆ

func (e *Encoder) EncodeMapLen(l int) error

func (*Encoder) EncodeMapSorted ΒΆ

func (e *Encoder) EncodeMapSorted(m map[string]interface{}) error

func (*Encoder) EncodeMulti ΒΆ

func (e *Encoder) EncodeMulti(v ...interface{}) error

func (*Encoder) EncodeNil ΒΆ

func (e *Encoder) EncodeNil() error

func (*Encoder) EncodeString ΒΆ

func (e *Encoder) EncodeString(v string) error

func (*Encoder) EncodeTime ΒΆ

func (e *Encoder) EncodeTime(tm time.Time) error

func (*Encoder) EncodeUint ΒΆ

func (e *Encoder) EncodeUint(n uint64) error

EncodeUnsignedNumber encodes an uint64 in 1, 2, 3, 5, or 9 bytes. Type of the number is lost during encoding.

func (*Encoder) EncodeUint8 ΒΆ

func (e *Encoder) EncodeUint8(n uint8) error

EncodeUint8 encodes an uint8 in 2 bytes preserving type of the number.

func (*Encoder) EncodeUint16 ΒΆ

func (e *Encoder) EncodeUint16(n uint16) error

EncodeUint16 encodes an uint16 in 3 bytes preserving type of the number.

func (*Encoder) EncodeUint32 ΒΆ

func (e *Encoder) EncodeUint32(n uint32) error

EncodeUint32 encodes an uint16 in 5 bytes preserving type of the number.

func (*Encoder) EncodeUint64 ΒΆ

func (e *Encoder) EncodeUint64(n uint64) error

EncodeUint64 encodes an uint16 in 9 bytes preserving type of the number.

func (*Encoder) EncodeValue ΒΆ

func (e *Encoder) EncodeValue(v reflect.Value) error

func (*Encoder) Reset ΒΆ

func (e *Encoder) Reset(w io.Writer)

Reset discards any buffered data, resets all state, and switches the writer to write to w.

func (*Encoder) ResetDict ΒΆ

func (e *Encoder) ResetDict(w io.Writer, dict map[string]int)

ResetDict is like Reset, but also resets the dict.

func (*Encoder) ResetWriter ΒΆ added in v5.4.0

func (e *Encoder) ResetWriter(w io.Writer)

func (*Encoder) SetCustomStructTag ΒΆ

func (e *Encoder) SetCustomStructTag(tag string)

SetCustomStructTag causes the Encoder to use a custom struct tag as fallback option if there is no msgpack tag.

func (*Encoder) SetOmitEmpty ΒΆ added in v5.3.2

func (e *Encoder) SetOmitEmpty(on bool)

SetOmitEmpty causes the Encoder to omit empty values by default.

func (*Encoder) SetSortMapKeys ΒΆ

func (e *Encoder) SetSortMapKeys(on bool) *Encoder

SetSortMapKeys causes the Encoder to encode map keys in increasing order. Supported map types are:

  • map[string]string
  • map[string]bool
  • map[string]interface{}

func (*Encoder) UseArrayEncodedStructs ΒΆ

func (e *Encoder) UseArrayEncodedStructs(on bool)

UseArrayEncodedStructs causes the Encoder to encode Go structs as msgpack arrays.

Example ΒΆ
package main

import (
	"bytes"
	"fmt"

	"github.com/vmihailenco/msgpack/v5"
)

func main() {
	type Item struct {
		Foo string
		Bar string
	}

	var buf bytes.Buffer
	enc := msgpack.NewEncoder(&buf)
	enc.UseArrayEncodedStructs(true)

	err := enc.Encode(&Item{Foo: "foo", Bar: "bar"})
	if err != nil {
		panic(err)
	}

	dec := msgpack.NewDecoder(&buf)
	v, err := dec.DecodeInterface()
	if err != nil {
		panic(err)
	}
	fmt.Println(v)
}
Output:
[foo bar]

func (*Encoder) UseCompactFloats ΒΆ

func (e *Encoder) UseCompactFloats(on bool)

UseCompactFloats causes the Encoder to chose a compact integer encoding for floats that can be represented as integers.

func (*Encoder) UseCompactInts ΒΆ

func (e *Encoder) UseCompactInts(on bool)

UseCompactEncoding causes the Encoder to chose the most compact encoding. For example, it allows to encode small Go int64 as msgpack int8 saving 7 bytes.

func (*Encoder) UseInternedStrings ΒΆ

func (e *Encoder) UseInternedStrings(on bool)

UseInternedStrings causes the Encoder to intern strings.

func (*Encoder) WithDict ΒΆ added in v5.1.3

func (e *Encoder) WithDict(dict map[string]int, fn func(*Encoder) error) error

func (*Encoder) Writer ΒΆ

func (e *Encoder) Writer() io.Writer

Writer returns the Encoder's writer.

type Marshaler ΒΆ

type Marshaler interface {
	MarshalMsgpack() ([]byte, error)
}

type MarshalerUnmarshaler ΒΆ

type MarshalerUnmarshaler interface {
	Marshaler
	Unmarshaler
}

type RawMessage ΒΆ

type RawMessage []byte

func (*RawMessage) DecodeMsgpack ΒΆ

func (m *RawMessage) DecodeMsgpack(dec *Decoder) error

func (RawMessage) EncodeMsgpack ΒΆ

func (m RawMessage) EncodeMsgpack(enc *Encoder) error

type Unmarshaler ΒΆ

type Unmarshaler interface {
	UnmarshalMsgpack([]byte) error
}

Directories ΒΆ

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL