sdk-go
sdk-go copied to clipboard
Question, maybe add to documentation request: HTTP request to CloudEvent
Team, a bit of a newbie question, but I couldn't find the answer in the docs and maybe other people will have the same issue. Is there any simple way to transform an incoming HTTP request to a CloudEvent and fail with an error if the request doesn't contain the correct headers to be a CloudEvent?
I am looking for something along the lines of cloudevents.NewEvent(req)
, but I understand that this should come from the HTTP binding.
I've found protocol/http.NewMessageFromHttpRequest(req)
but again this seems to be transforming to an internal representation that is still one step away from being a CloudEvent.
If there is one, it will be great to add that into the docs.. as most of the docs show how to create Handler functions that will automatically parse the HTTP request into a CloudEvent, but not the inner workings.
If this is not recommended for some reason, it will be also good to add that to the docs.
Feel free to create a PR with some documentation where you'd expect to see it within the docs/
directory. I believe you could do something like this:
import (
"github.com/cloudevents/sdk-go/v2/binding"
cehttp "github.com/cloudevents/sdk-go/v2/protocol/http"
)
...
var req *http.Request
msg := cehttp.NewMessageFromHttpRequest(req)
event, err := binding.ToEvent(context.Background(), msg, nil)
if err != nil {
panic(err)
}
fmt.Println(event.ID())
@dan-j thanks for sharing that example, that is really helpful. But I wonder what is your opinion on making that simple and more intuitive for users, meaning something like:
event, err := cehttp.NewEventFromHttpRequest(req);
This is just encapsulating the code that you shared...
I am happy to send a PR for this, if the team behind the SDK think this is a good or OK idea :)
Cheers
What to add a PR for this utility method?
Where should this method live?
I think a new file in https://github.com/cloudevents/sdk-go/tree/main/v2/protocol/http would be fine, and you could export it to the top level via https://github.com/cloudevents/sdk-go/blob/main/v2/alias.go
I've got most of a first pass put together, but I'm getting a segfault that I've traced to the transformers invocation in the ToEvent return statement:
https://github.com/cloudevents/sdk-go/blob/c623f8bfd7c3d7206f0aec5730460d137e3f42a8/v2/binding/to_event.go#L61
This struck me as potentially an existing bug, so I wanted to surface this quickly in case it was already identified.
interesting, any idea what the segfault is about? able to make a unit test to repro?
Yes, the unit test coverage I wrote for the helper function consistently reproduces. I've pushed what I have to a draft PR to illustrate: https://github.com/cloudevents/sdk-go/pull/799