-
Notifications
You must be signed in to change notification settings - Fork 217
/
codec_structured.go
44 lines (36 loc) · 1.03 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
41
42
43
44
package http
import (
"context"
"encoding/json"
"fmt"
"net/http"
"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) {
header := http.Header{}
header.Set("Content-Type", cloudevents.ApplicationCloudEventsJSON)
body, err := json.Marshal(e)
if err != nil {
return nil, err
}
msg := &Message{
Header: header,
Body: body,
}
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 http.Message")
}
event := cloudevents.New(version)
err := json.Unmarshal(m.Body, &event)
return &event, err
}