/
codec_structured.go
40 lines (33 loc) · 1.01 KB
/
codec_structured.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
package pubsub
import (
"context"
"encoding/json"
"fmt"
"github.com/cloudevents/sdk-go/pkg/cloudevents"
"github.com/cloudevents/sdk-go/pkg/cloudevents/transport"
)
// CodecStructured represents an structured http transport codec for all versions.
// Intended to be used as a base class.
type CodecStructured struct {
Encoding Encoding
}
func (v CodecStructured) encodeStructured(ctx context.Context, e cloudevents.Event) (transport.Message, error) {
data, err := json.Marshal(e)
if err != nil {
return nil, err
}
msg := &Message{
Attributes: map[string]string{StructuredContentType: cloudevents.ApplicationCloudEventsJSON},
Data: data,
}
return msg, nil
}
func (v CodecStructured) decodeStructured(ctx context.Context, version string, msg transport.Message) (*cloudevents.Event, error) {
m, ok := msg.(*Message)
if !ok {
return nil, fmt.Errorf("failed to convert transport.Message to pubsub.Message")
}
event := cloudevents.New(version)
err := json.Unmarshal(m.Data, &event)
return &event, err
}