0

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).

kernel0707
  • 314
  • 2
  • 11
  • What use cases of this passed value? Why should you use middleware to create this value? – Oleg Butuzov Aug 04 '21 at 13:16
  • 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 – kernel0707 Aug 04 '21 at 13:19
  • @OlegButuzov I have updated the question to clear it out further. – kernel0707 Aug 04 '21 at 13:23
  • It's easier to pass something to context than substitute response writer and change response in middleware. so yeah, you can do it in this way. – Oleg Butuzov Aug 04 '21 at 13:29
  • 1
    @kernel0707 If I understand clearly it does not seem usable, I don't understand why would you need multiple middlewares with Context to set and get query parameters which can be accessed directly in handlers – Chandan Aug 22 '21 at 13:49

0 Answers0