-
Notifications
You must be signed in to change notification settings - Fork 55
/
proto.go
55 lines (42 loc) · 1015 Bytes
/
proto.go
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
/**
* @Author: fuxiao
* @Email: 576101059@qq.com
* @Date: 2022/5/14 10:47 上午
* @Desc: TODO
*/
package proto
import (
"errors"
"github.com/gogo/protobuf/proto"
)
const Name = "proto"
var DefaultCodec = &codec{}
type codec struct{}
// Name 编解码器名称
func (codec) Name() string {
return Name
}
// Marshal 编码
func (codec) Marshal(v interface{}) ([]byte, error) {
msg, ok := v.(proto.Message)
if !ok {
return nil, errors.New("can't marshal a value that not implements proto.Buffer interface")
}
return proto.Marshal(msg)
}
// Unmarshal 解码
func (codec) Unmarshal(data []byte, v interface{}) error {
msg, ok := v.(proto.Message)
if !ok {
return errors.New("can't unmarshal to a value that not implements proto.Buffer")
}
return proto.Unmarshal(data, msg)
}
// Marshal 编码
func Marshal(v interface{}) ([]byte, error) {
return DefaultCodec.Marshal(v)
}
// Unmarshal 解码
func Unmarshal(data []byte, v interface{}) error {
return DefaultCodec.Unmarshal(data, v)
}