natspb.go 598 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
11
package natspb

import (
	"errors"

	"github.com/nats-io/nats.go"
	"google.golang.org/protobuf/proto"
)

type protoEncoder struct{}

Rutger Broekhoff's avatar
Rutger Broekhoff committed
12
13
14
15
func NewEncoder() nats.Encoder {
	return protoEncoder{}
}

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func (p protoEncoder) Encode(_ string, v interface{}) ([]byte, error) {
	msg, ok := v.(proto.Message)
	if !ok {
		return nil, errors.New("v is not proto.Message")
	}
	return proto.Marshal(msg)
}

func (p protoEncoder) Decode(_ string, data []byte, vPtr interface{}) error {
	msg, ok := vPtr.(proto.Message)
	if !ok {
		return errors.New("vPtr is not proto.Message")
	}
	return proto.Unmarshal(data, msg)
}