2022-01-13 00:39:22 +03:00
|
|
|
// Package msgpack provides a msgpack codec
|
2022-01-13 00:34:00 +03:00
|
|
|
package msgpack // import "go.unistack.org/micro-codec-msgpack/v3"
|
|
|
|
|
|
|
|
import (
|
2024-09-17 12:42:07 +03:00
|
|
|
"reflect"
|
2022-01-13 00:34:00 +03:00
|
|
|
|
|
|
|
"github.com/vmihailenco/msgpack/v5"
|
2023-03-05 22:09:04 +03:00
|
|
|
pb "go.unistack.org/micro-proto/v3/codec"
|
2022-01-13 00:34:00 +03:00
|
|
|
"go.unistack.org/micro/v3/codec"
|
|
|
|
rutil "go.unistack.org/micro/v3/util/reflect"
|
|
|
|
)
|
|
|
|
|
|
|
|
type msgpackCodec struct {
|
|
|
|
opts codec.Options
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *msgpackCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error) {
|
|
|
|
if v == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
options := c.opts
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
|
2024-09-17 12:42:07 +03:00
|
|
|
if options.Flatten {
|
|
|
|
if nv, err := rutil.StructFieldByTag(v, options.TagName, "flatten"); err == nil {
|
|
|
|
v = nv
|
|
|
|
}
|
2022-01-13 00:34:00 +03:00
|
|
|
}
|
|
|
|
|
2023-03-05 22:09:04 +03:00
|
|
|
switch m := v.(type) {
|
|
|
|
case *codec.Frame:
|
|
|
|
return m.Data, nil
|
|
|
|
case *pb.Frame:
|
2022-01-13 00:34:00 +03:00
|
|
|
return m.Data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return msgpack.Marshal(v)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *msgpackCodec) Unmarshal(b []byte, v interface{}, opts ...codec.Option) error {
|
|
|
|
if len(b) == 0 || v == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
options := c.opts
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
|
2024-09-17 12:42:07 +03:00
|
|
|
if options.Flatten {
|
|
|
|
if nv, err := rutil.StructFieldByTag(v, options.TagName, "flatten"); err == nil {
|
|
|
|
v = nv
|
|
|
|
rv := reflect.ValueOf(v)
|
|
|
|
if rv.Kind() != reflect.Pointer &&
|
|
|
|
rv.Kind() != reflect.Map {
|
|
|
|
v = reflect.New(rv.Type()).Interface()
|
|
|
|
}
|
|
|
|
}
|
2022-01-13 00:34:00 +03:00
|
|
|
}
|
|
|
|
|
2023-03-05 22:09:04 +03:00
|
|
|
switch m := v.(type) {
|
|
|
|
case *codec.Frame:
|
|
|
|
m.Data = b
|
|
|
|
return nil
|
|
|
|
case *pb.Frame:
|
2022-01-13 00:34:00 +03:00
|
|
|
m.Data = b
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return msgpack.Unmarshal(b, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *msgpackCodec) String() string {
|
|
|
|
return "msgpack"
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCodec(opts ...codec.Option) codec.Codec {
|
|
|
|
return &msgpackCodec{opts: codec.NewOptions(opts...)}
|
|
|
|
}
|