I am using Echo framework and want to pass the Go's built-in context.Context
underlying echo.Context after setting some custom values.
To achieve it, I think I could first apply Set(key string, val interface{})
method of echo.Context
and then extract the underlying context.Context
.
Question is is it possible to do it this way? In other words, does echo.Context.Set(...)
sets the value directly on the context.Context
just like WithValue
does? Or should I take extra steps to copy my custom entries down.
P.S. I do not want to pass echo.Context
to deeper layers of my app, that's why I do not want to directly use it but get the referring context.Context
Method 1: Reimplement the echo.Context.Get and echo.Context.Set methods to manipulate the ctx.Request().Context() object.
Disadvantages: http.Request.WithContext will be called once for each Set method, and *http.Request will be copied once. See the implementation of WithContext method for details.
Method 2: Reimplement the echo.Context.Get and echo.Context.Set methods to manipulate the contextValueData2 object, and set http.Request.WithContext to a custom context.Context contextValueData2.
Disadvantages: Before go1.13, context.Context requires Type assertions. Don't implement the context.Context method. Compared with method 1, the implementation only requires WithContext once.
It is recommended to use method 1, which is clear and simple, and method 2 is complicated and not fully tested.
The example import package uses gopath, and the implementation of this feature also reflects the advantage of echo.Context as an interface.