Skip to content

Commit a718752

Browse files
graysiden3wscott
andauthored
Helper function to create event from HTTP Request or Response (#799)
* Helper function to create event from HTTP Request or Response * Add missing use of encoding options and remove redundant function call Signed-off-by: Adam Ross <adamross@google.com> * Update v2/protocol/http/utility.go Co-authored-by: Scott Nichols <n3wscott@tableflip.dev> * Update v2/protocol/http/utility.go Co-authored-by: Scott Nichols <n3wscott@tableflip.dev> * Update v2/protocol/http/utility.go Co-authored-by: Scott Nichols <n3wscott@tableflip.dev> * Update v2/protocol/http/utility.go Co-authored-by: Scott Nichols <n3wscott@tableflip.dev> * capitalize HTTP and WIP clean-up Signed-off-by: Adam Ross <adamross@google.com> Signed-off-by: Adam Ross <adamross@google.com> Co-authored-by: Scott Nichols <n3wscott@tableflip.dev>
1 parent c623f8b commit a718752

File tree

5 files changed

+147
-0
lines changed

5 files changed

+147
-0
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,19 @@ func main() {
8383
}
8484
```
8585

86+
## Create a CloudEvent from an HTTP Request
87+
88+
```go
89+
func handler(w http.ResponseWriter, r *http.Request) {
90+
event, err := cloudevents.NewCloudEventFromHTTPRequest(r)
91+
if err != nil {
92+
log.Print("failed to parse CloudEvent from request: %v", err)
93+
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
94+
}
95+
w.Write([]byte(*event.String()))
96+
}
97+
```
98+
8699
## Serialize/Deserialize a CloudEvent
87100

88101
To marshal a CloudEvent into JSON:

docs/index.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,19 @@ func main() {
8181
}
8282
```
8383

84+
## Create a CloudEvent from an HTTP Request
85+
86+
```go
87+
func handler(w http.ResponseWriter, r *http.Request) {
88+
event, err := cloudevents.NewCloudEventFromHTTPRequest(r)
89+
if err != nil {
90+
log.Print("failed to parse CloudEvent from request: %v", err)
91+
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
92+
}
93+
w.Write([]byte(*event.String()))
94+
}
95+
```
96+
8497
## Serialize/Deserialize a CloudEvent
8598

8699
To marshal a CloudEvent into JSON:

v2/alias.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,10 @@ var (
134134

135135
ToMessage = binding.ToMessage
136136

137+
// Event Creation
138+
NewEventFromHTTPRequest = http.NewEventFromHTTPRequest
139+
NewEventFromHTTPResponse = http.NewEventFromHTTPResponse
140+
137141
// HTTP Messages
138142

139143
WriteHTTPRequest = http.WriteRequest

v2/protocol/http/utility.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
Copyright 2022 The CloudEvents Authors
3+
SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package http
7+
8+
import (
9+
"context"
10+
nethttp "net/http"
11+
12+
"github.com/cloudevents/sdk-go/v2/binding"
13+
"github.com/cloudevents/sdk-go/v2/event"
14+
)
15+
16+
// NewEventFromHTTPRequest returns an Event.
17+
func NewEventFromHTTPRequest(req *nethttp.Request) (*event.Event, error) {
18+
msg := NewMessageFromHttpRequest(req)
19+
return binding.ToEvent(context.Background(), msg)
20+
}
21+
22+
// NewEventFromHTTPResponse returns an Event.
23+
func NewEventFromHTTPResponse(resp *nethttp.Response) (*event.Event, error) {
24+
msg := NewMessageFromHttpResponse(resp)
25+
return binding.ToEvent(context.Background(), msg)
26+
}

v2/protocol/http/utility_test.go

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/*
2+
Copyright 2022 The CloudEvents Authors
3+
SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package http
7+
8+
import (
9+
"bytes"
10+
"context"
11+
"io/ioutil"
12+
"net/http"
13+
"net/http/httptest"
14+
"testing"
15+
16+
"github.com/stretchr/testify/require"
17+
18+
"github.com/cloudevents/sdk-go/v2/binding"
19+
"github.com/cloudevents/sdk-go/v2/event"
20+
"github.com/cloudevents/sdk-go/v2/test"
21+
)
22+
23+
func TestNewEventFromHttpRequest(t *testing.T) {
24+
tests := []struct {
25+
name string
26+
encoding binding.Encoding
27+
}{{
28+
name: "Structured encoding",
29+
encoding: binding.EncodingStructured,
30+
}, {
31+
name: "Binary encoding",
32+
encoding: binding.EncodingBinary,
33+
}}
34+
35+
for _, tt := range tests {
36+
test.EachEvent(t, test.Events(), func(t *testing.T, eventIn event.Event) {
37+
t.Run(tt.name, func(t *testing.T) {
38+
ctx := context.TODO()
39+
if tt.encoding == binding.EncodingStructured {
40+
ctx = binding.WithForceStructured(ctx)
41+
} else if tt.encoding == binding.EncodingBinary {
42+
ctx = binding.WithForceBinary(ctx)
43+
}
44+
45+
req := httptest.NewRequest("POST", "http://localhost", nil)
46+
require.NoError(t, WriteRequest(ctx, (*binding.EventMessage)(&eventIn), req))
47+
48+
got, err := NewEventFromHTTPRequest(req)
49+
require.NoError(t, err)
50+
test.AssertEvent(t, *got, test.IsValid())
51+
})
52+
})
53+
}
54+
}
55+
56+
func TestNewEventFromHttpResponse(t *testing.T) {
57+
tests := []struct {
58+
name string
59+
resp *http.Response
60+
}{{
61+
name: "Structured encoding",
62+
resp: &http.Response{
63+
Header: http.Header{
64+
"Content-Type": {event.ApplicationCloudEventsJSON},
65+
},
66+
Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"data":"foo","datacontenttype":"application/json","id":"id","source":"source","specversion":"1.0","type":"type"}`))),
67+
ContentLength: 113,
68+
},
69+
}, {
70+
name: "Binary encoding",
71+
resp: &http.Response{
72+
Header: func() http.Header {
73+
h := http.Header{}
74+
h.Set("ce-specversion", "1.0")
75+
h.Set("ce-source", "unittest")
76+
h.Set("ce-type", "unittest")
77+
h.Set("ce-id", "unittest")
78+
h.Set("Content-Type", "application/json")
79+
return h
80+
}(),
81+
},
82+
}}
83+
84+
for _, tt := range tests {
85+
t.Run(tt.name, func(t *testing.T) {
86+
got, err := NewEventFromHTTPResponse(tt.resp)
87+
require.NoError(t, err)
88+
test.AssertEvent(t, *got, test.IsValid())
89+
})
90+
}
91+
}

0 commit comments

Comments
 (0)