I am using echo to build a web server in go. What is the best way to pass objects around middlewares and a handler apart from using context.Set method?
For example, let's consider the following case:
func mw(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Conext) error {
var value TypeX = // load value of type TypeX based on query parameters
c.Set("key", value)
return next(c)
}
}
func h1(c echo.context) error {
value := c.Get("key").(TypeX)
return c.JSON(http.StatusOk, value.H1())
}
func h2(c echo.context) error {
value := c.Get("key").(TypeX)
return c.JSON(http.StatusOk, value.H2())
}
func registerRoute(e *echo.Echo) {
e.Get("/test", h)
}
Is there any way to get rid of get/set methods? It seems like an unclean way of doing this operation. I am open to complete refactoring, creating new structures/interfaces to make this happen.
To take this example further, lets say my apis can fall into bucket1, bucket2, bucket3. Value
would call the method b1
, b2
, b3
based on which bucked it falls in. These buckets can be identified by adding them as middleware mwB1
, mwB2
, mwB3
each of which calls the respective method. Hence, all my apis would first call the middleware mw
; then one of mwB1
, mwB2
, mwB3
and finally the actual handler, something like, e.Get("/test", h, mw, mwB2)
. I don't want to load value
everywhere and get/set seems unclean to me (unless that is the standard way of doing this).