-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprotobufs.go
More file actions
49 lines (42 loc) · 1.13 KB
/
protobufs.go
File metadata and controls
49 lines (42 loc) · 1.13 KB
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
package protobufs
import (
"github.com/openziti/channel/v4"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
"reflect"
)
type TypedMessage interface {
proto.Message
GetContentType() int32
}
func MarshalProto(contentType int32, msg proto.Message) channel.Envelope {
b, err := proto.Marshal(msg)
if err != nil {
return channel.NewErrorEnvelope(errors.Wrapf(err, "failed to marshal %v", reflect.TypeOf(msg)))
}
return channel.NewMessage(contentType, b)
}
func MarshalTyped(msg TypedMessage) channel.Envelope {
return MarshalProto(msg.GetContentType(), msg)
}
func TypedResponse(message TypedMessage) TypedResponseImpl {
return TypedResponseImpl{
TypedMessage: message,
}
}
type TypedResponseImpl struct {
TypedMessage
}
func (self TypedResponseImpl) Unmarshall(responseMsg *channel.Message, err error) error {
if err != nil {
return err
}
if responseMsg.ContentType != self.GetContentType() {
return errors.Errorf("unexpected response type %v. expected %v",
responseMsg.ContentType, self.GetContentType())
}
if err = proto.Unmarshal(responseMsg.Body, self.TypedMessage); err != nil {
return err
}
return nil
}