cloudevents/sdk-go

Context issue when using protocol's incoming channel with gin framework

tank-500m opened this issue · 0 comments

When creating an HTTP receiver using the gin framework, there is an issue with the context when using the incoming channel from the CloudEvents SDK protocol. The context of the message received through the protocol's incoming channel is different from the gin context created with the HTTP request.

The message context is passed through the channel provided by the CloudEvents SDK protocol, while the gin context is created along with the HTTP request, resulting in two different contexts.

This can cause problems if you need to access the gin context during message processing. For example, you may not be able to access request headers, query parameters, or other information provided by the gin context.

To resolve this issue, you should consider either including the gin context in the message context or passing the gin context separately during message processing. However, even if you include the gin context in the message context, there is no guarantee that a proper response will be sent to the client if an error occurs in the Respond function.

this sample code

package main

import (
	cloudevents "github.com/cloudevents/sdk-go/v2"
	cehttp "github.com/cloudevents/sdk-go/v2/protocol/http"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.New()

	var p *cehttp.Protocol
	p, _ = cloudevents.NewHTTP()

	/*
		input CloudEvent example:
		{
			"specversion": "1.0",
			"type": "com.example.test",
			"source": "http://example.com",
			"id": UUID value,
			"topic": topicID,  // #extension for test, path param's topic id == this
			"data": {
				"message": "Hello, World!"
			}
		}
	*/

	r.POST("/topics/:topicId/", func(c *gin.Context) {
		ceh, _ := cloudevents.NewHTTPReceiveHandler(c, p, func(e cloudevents.Event) {
			if c.Param("topicId") != e.Extensions()["topicid"] {
				panic("context issue.....!")
			}
		})

		ceh.ServeHTTP(c.Writer, c.Request)
	})

	r.Run(":9192")
}