-
Notifications
You must be signed in to change notification settings - Fork 216
/
request_encoder.go
78 lines (65 loc) · 2.01 KB
/
request_encoder.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package http
import (
"context"
"io"
"io/ioutil"
"net/http"
"github.com/cloudevents/sdk-go/pkg/binding"
"github.com/cloudevents/sdk-go/pkg/binding/format"
"github.com/cloudevents/sdk-go/pkg/binding/spec"
"github.com/cloudevents/sdk-go/pkg/cloudevents/types"
)
// Fill the provided req with the message m.
// Using context you can tweak the encoding processing (more details on binding.Translate documentation).
func EncodeHttpRequest(ctx context.Context, m binding.Message, req *http.Request, transformerFactories binding.TransformerFactories) error {
structuredEncoder := (*httpRequestEncoder)(req)
binaryEncoder := (*httpRequestEncoder)(req)
_, err := binding.Encode(
ctx,
m,
structuredEncoder,
binaryEncoder,
transformerFactories,
)
return err
}
type httpRequestEncoder http.Request
func (b *httpRequestEncoder) SetStructuredEvent(ctx context.Context, format format.Format, event io.Reader) error {
b.Header.Set(ContentType, format.MediaType())
b.Body = ioutil.NopCloser(event)
return nil
}
func (b *httpRequestEncoder) Start(ctx context.Context) error {
return nil
}
func (b *httpRequestEncoder) End() error {
return nil
}
func (b *httpRequestEncoder) SetData(reader io.Reader) error {
b.Body = ioutil.NopCloser(reader)
return nil
}
func (b *httpRequestEncoder) SetAttribute(attribute spec.Attribute, value interface{}) error {
// Http headers, everything is a string!
s, err := types.Format(value)
if err != nil {
return err
}
if attribute.Kind() == spec.DataContentType {
b.Header.Add(ContentType, s)
} else {
b.Header.Add(prefix+attribute.Name(), s)
}
return nil
}
func (b *httpRequestEncoder) SetExtension(name string, value interface{}) error {
// Http headers, everything is a string!
s, err := types.Format(value)
if err != nil {
return err
}
b.Header.Add(prefix+name, s)
return nil
}
var _ binding.StructuredEncoder = (*httpRequestEncoder)(nil) // Test it conforms to the interface
var _ binding.BinaryEncoder = (*httpRequestEncoder)(nil) // Test it conforms to the interface