func Marshal

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

Marshal 返回v的MessagePack编码。

Example

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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)
1
bar

Example (AsArray)

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
type Item struct {
	_msgpack struct{} `msgpack:",asArray"`
	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)
1
[foo bar]

Example (MapStringInterface)

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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"])
1
2
foo = 1
hello = world

Example (OmitEmpty)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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)
1
2
item: "\x82\xa3Foo\xa5hello\xa3Bar\xa0"
item2: "\x81\xa3Foo\xa5hello"

func PutDecoder

1
func PutDecoder(dec *Decoder)

func PutEncoder

1
func PutEncoder(enc *Encoder)

func Register

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

Register注册一个值的编码器和解码器功能。这是低级API,在大多数情况下,您应该更喜欢实现Marshaler / CustomEncoder和Unmarshaler / CustomDecoder接口。

func RegisterExt

1
func RegisterExt(id int8, value interface{})

RegisterExt 在提供的ID下记录由该类型的值标识的类型。 该ID将标识作为接口变量发送或接收的值的具体类型。 仅将要注册的类型将作为接口值的实现进行注册。 期望仅在初始化期间使用,如果类型和id之间的映射不是双射,它会感到恐慌。

Example

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package msgpack_test

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

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

func init() {
	msgpack.RegisterExt(1, (*EventTime)(nil))
}

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

var _ msgpack.Marshaler = (*EventTime)(nil)
var _ msgpack.Unmarshaler = (*EventTime)(nil)

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 ExampleRegisterExt() {
	b, err := msgpack.Marshal(&EventTime{time.Unix(123456789, 123)})
	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())

	// Output: 1973-11-29 21:33:09.000000123 +0000 UTC
	// 1973-11-29 21:33:09.000000123 +0000 UTC
}
1
2
1973-11-29 21:33:09.000000123 +0000 UTC
1973-11-29 21:33:09.000000123 +0000 UTC

func Unmarshal

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

Unmarshal 解码MessagePack编码的数据,并将结果存储在v指向的值中。

type CustomDecoder

1
2
3
type CustomDecoder interface {
	DecodeMsgpack(*Decoder) error
}

type CustomEncoder

1
2
3
type CustomEncoder interface {
	EncodeMsgpack(*Encoder) error
}

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package msgpack_test

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 ExampleCustomEncoder() {
	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}
}
1
msgpack_test.customStruct{S:"hello", N:42}

type Decoder

1
2
3
4
5

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

Decoder从输入流读取和解码MessagePack值。

func GetDecoder

1
func GetDecoder() *Decoder

func NewDecoder

1
func NewDecoder(r io.Reader) *Decoder

NewDecoder返回从r读取的新解码器。

解码器引入自己的缓冲,并且可能从r读取超出请求的MessagePack值的数据。可以通过传递实现io.ByteScanner接口的读取器来禁用缓冲。

func (*Decoder) Buffered

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

Buffered返回解码器缓冲区中剩余数据的读取器。读取器在下一次调用Decode之前一直有效。

func (*Decoder) Decode

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

nolint:gocyclo

func (*Decoder) DecodeArrayLen

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

DecodeArrayLen解码数组长度。当数组为nil时,长度为-1。

func (*Decoder) DecodeBool

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

func (*Decoder) DecodeBytes

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

func (*Decoder) DecodeBytesLen

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

func (*Decoder) DecodeDuration

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

func (*Decoder) DecodeExtHeader

1
func (d *Decoder) DecodeExtHeader() (typeID int8, length int, err error)

func (*Decoder) DecodeFloat32

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

func (*Decoder) DecodeFloat64

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

DecodeFloat64 将msgpack float32 / 64解码为Go float64。

func (*Decoder) DecodeInt

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

func (*Decoder) DecodeInt16

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

func (*Decoder) DecodeInt32

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

func (*Decoder) DecodeInt64

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

DecodeInt64 将msgpack int8 / 16/32/64和uint8 / 16/32/64解码为Go int64。

func (*Decoder) DecodeInt8

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

func (*Decoder) DecodeInterface

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

DecodeInterface将值解码为接口。它返回以下类型::

1
2
3
4
5
6
7
8
9
- 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。例如,如果要解码数字,最好对负数使用DecodeInt64,对正数使用DecodeUint64。

func (*Decoder) DecodeInterfaceLoose

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

DecodeInterfaceLoose类似于DecodeInterface,不同之处在于:

1
2
3
- int8, int16, and int32 are converted to int64,
- uint8, uint16, and uint32 are converted to uint64,
- float32 is converted to float64.

func (*Decoder) DecodeMap

1
func (d *Decoder) DecodeMap() (interface{}, error)

func (*Decoder) DecodeMapLen

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

DecodeMapLen 解码map长度。映射为零时,长度为-1。

func (*Decoder) DecodeMulti

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

func (*Decoder) DecodeNil

1
func (d *Decoder) DecodeNil() error

func (*Decoder) DecodeRaw

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

func (*Decoder) DecodeSlice

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

func (*Decoder) DecodeString

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

func (*Decoder) DecodeTime

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

func (*Decoder) DecodeUint

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

func (*Decoder) DecodeUint16

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

func (*Decoder) DecodeUint32

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

func (*Decoder) DecodeUint64

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

DecodeUint64 将msgpack int8 / 16/32/64和uint8 / 16/32/64解码为Go uint64。

func (*Decoder) DecodeUint8

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

func (*Decoder) DecodeValue

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

func (*Decoder) DisallowUnknownFields

1
func (d *Decoder) DisallowUnknownFields(on bool)

当目标是一个结构并且输入包含与目标中任何未忽略的导出字段都不匹配的对象键时,DisallowUnknownFields会导致解码器返回错误。

func (*Decoder) PeekCode

1
func (d *Decoder) PeekCode() (codes.Code, error)

PeekCode不提高阅读器的情况下返回下一个MessagePack代码。子软件包msgpack / codes定义可用代码列表。

func (*Decoder) Query

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

Query 从msgpack流中提取查询指定的数据,并跳过其他任何数据。查询由映射键和以点分隔的数组索引组成,例如key1.0.key2。

Example

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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])
1
2
phones are [12345 54321]
2nd phone is 54321

func (*Decoder) ReadFull

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

ReadFull将len(buf)个字节恰好读取到buf中。

func (*Decoder) Reset

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

Reset 将丢弃所有缓冲的数据,重置所有状态,并将缓冲的读取器切换为从r读取。

func (*Decoder) ResetBytes

1
func (d *Decoder) ResetBytes(data []byte)

func (*Decoder) SetDecodeMapFunc

1
func (d *Decoder) SetDecodeMapFunc(fn func(*Decoder) (interface{}, error))

Example

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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)

dec.SetDecodeMapFunc(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)
}
1
2
fmt.Printf("%#v", out)
map[string]string{"hello":"world"}

func (*Decoder) Skip

1
func (d *Decoder) Skip() error

Skip 跳过下一个值。

func (*Decoder) UseCustomStructTag

1
func (d *Decoder) UseCustomStructTag(tag string)

如果没有msgpack标签,UseCustomStructTag会使解码器将提供的标签用作后备选项。

func (*Decoder) UseDecodeInterfaceLoose

1
func (d *Decoder) UseDecodeInterfaceLoose(on bool)

UseDecodeInterfaceLoose使解码器使用DecodeInterfaceLoose将msgpack值解码为Go接口{}。

func (*Decoder) UseJSONTag

1
func (d *Decoder) UseJSONTag(on bool)

如果没有msgpack标签,UseJSONTag会使Decoder使用json struct标签作为后备选项。

type Encoder

1
2
3
type Encoder struct {
	// contains filtered or unexported fields
}

func GetEncoder

1
func GetEncoder() *Encoder

func NewEncoder

1
func NewEncoder(w io.Writer) *Encoder

NewEncoder 返回一个写入w的新编码器。

func (*Encoder) Encode

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

func (*Encoder) EncodeArrayLen

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

func (*Encoder) EncodeBool

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

func (*Encoder) EncodeBytes

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

func (*Encoder) EncodeBytesLen

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

func (*Encoder) EncodeDuration

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

func (*Encoder) EncodeExtHeader

1
func (e *Encoder) EncodeExtHeader(typeID int8, length int) error

func (*Encoder) EncodeFloat32

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

func (*Encoder) EncodeFloat64

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

func (*Encoder) EncodeInt

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

EncodeNumber以1、2、3、5或9个字节编码int64。数字类型在编码过程中丢失。

func (*Encoder) EncodeInt16

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

EncodeInt16将int16编码为3个字节,保留数字的类型。

func (*Encoder) EncodeInt32

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

EncodeInt32将int32编码为5个字节,保留数字的类型。

func (*Encoder) EncodeInt64

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

EncodeInt64将int64编码为9个字节,并保留数字的类型。

func (*Encoder) EncodeInt8

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

EncodeInt8将int8编码为2个字节,以保留数字的类型。

func (*Encoder) EncodeMapLen

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

func (*Encoder) EncodeMulti

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

func (*Encoder) EncodeNil

1
func (e *Encoder) EncodeNil() error

func (*Encoder) EncodeString

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

func (*Encoder) EncodeTime

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

func (*Encoder) EncodeUint

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

EncodeUnsignedNumber以1、2、3、5或9个字节编码uint64。数字类型在编码过程中丢失。

func (*Encoder) EncodeUint16

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

EncodeUint16将uint16编码为3个字节,以保留数字的类型。

func (*Encoder) EncodeUint32

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

EncodeUint32将uint16编码为5个字节,以保留数字的类型。

func (*Encoder) EncodeUint64

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

EncodeUint64将uint16编码为9个字节,以保留数字的类型。

func (*Encoder) EncodeUint8

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

EncodeUint8将uint8编码为2个字节,以保留数字的类型。

func (*Encoder) EncodeValue

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

func (*Encoder) Reset

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

func (*Encoder) SortMapKeys

1
func (e *Encoder) SortMapKeys(on bool) *Encoder

SortMapKeys使编码器按递增顺序对map关键字进行编码。支持的map类型为:

1
2
- map[string]string
- map[string]interface{}

func (*Encoder) StructAsArray

1
func (e *Encoder) StructAsArray(on bool)

StructAsArray使编码器将Go结构编码为msgpack数组。

func (*Encoder) UseCompactFloats

1
func (e *Encoder) UseCompactFloats(on bool)

UseCompactFloats使编码器为可以表示为整数的浮点数选择紧凑的整数编码。

func (*Encoder) UseCompactInts

1
func (e *Encoder) UseCompactInts(on bool)

UseCompactEncoding使编码器选择最紧凑的编码。例如,它允许将小的Go int64编码为msgpack int8,节省7个字节。

func (*Encoder) UseCustomStructTag

1
func (e *Encoder) UseCustomStructTag(tag string)

如果没有msgpack标记,则UseCustomStructTag会导致Encoder使用自定义结构标记作为后备选项。

func (*Encoder) UseJSONTag

1
func (e *Encoder) UseJSONTag(on bool)

如果没有msgpack标签,UseJSONTag会导致Encoder使用json struct标签作为后备选项。

func (*Encoder) Writer

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

Writer 返回Encoder’s writer.

type Marshaler

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

}

type RawMessage

1
type RawMessage []byte

func (*RawMessage) DecodeMsgpack

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

func (RawMessage) EncodeMsgpack

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

type Unmarshaler

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