Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix EventReceiver does not propagate request context #540

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion v2/client/http_receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (r *EventReceiver) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
r.p.ServeHTTP(rw, req)
}()

ctx := context.Background()
ctx := req.Context()
msg, respFn, err := r.p.Respond(ctx)
if err != nil {
//lint:ignore SA9003 TODO: Branch left empty
Expand Down
66 changes: 66 additions & 0 deletions v2/client/http_receiver_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package client_test

import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"

cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/cloudevents/sdk-go/v2/client"
"github.com/stretchr/testify/require"
)

func TestEventReceiverServeHTTP_WithContext(t *testing.T) {
type ctxKey string
const ctxKeyTest ctxKey = "testKey"

middleware := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = context.WithValue(ctx, ctxKeyTest, "testValue")
next.ServeHTTP(w, r.WithContext(ctx))
})
}

eventReceiver := func(ctx context.Context) error {
v, ok := ctx.Value(ctxKeyTest).(string)
if !ok {
t.Errorf("invalid context value type: %v", v)
return errors.New("invalid context")
}
if v != "testValue" {
t.Errorf("invalid context value: %s", v)
return errors.New("invalid context")
}
return nil
}

p, err := cloudevents.NewHTTP()
if err != nil {
t.Fatal(err)
}
httpHandler, err := client.NewHTTPReceiveHandler(context.Background(), p, eventReceiver)
if err != nil {
t.Fatal(err)
}
c, err := cloudevents.NewDefaultClient()
if err != nil {
t.Fatal(err)
}

mux := http.NewServeMux()
mux.Handle("/test", middleware(httpHandler))
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)

event := cloudevents.NewEvent()
event.SetSource("testSource")
event.SetType("testType")
ctx := context.Background()
ctx = cloudevents.ContextWithTarget(ctx, ts.URL+"/test")

result := c.Send(ctx, event)
require.True(t, cloudevents.IsACK(result))
}