/
proto.go
37 lines (31 loc) · 1001 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
package proto
import (
"errors"
"google.golang.org/protobuf/proto"
)
// Convenience variable for simpler usage in gokv store options.
//
// options := redis.Options{
// Encoding: proto.Codec,
// }
var Codec = PBcodec{}
// PBcodec encodes/decodes Go values to/from protocol buffers.
type PBcodec struct{}
// Marshal encodes a proto message struct into the binary wire format.
// Passed value can't be any Go value, but must be an object of a proto message struct.
func (c PBcodec) Marshal(v any) ([]byte, error) {
msg, ok := v.(proto.Message)
if !ok {
return nil, errors.New("error casting interface to proto")
}
return proto.Marshal(msg)
}
// Unmarshal parses a wire-format message in proto message struct.
// Passed value can't be any Go value, but must be an object of a proto message struct.
func (c PBcodec) Unmarshal(data []byte, v any) error {
msg, ok := v.(proto.Message)
if !ok {
return errors.New("error casting interface to proto")
}
return proto.Unmarshal(data, msg)
}