2

How do I pass along some extra variables to an Echo mux handler?

I have registered a route like this in main.go:

 e.GET("/search/:query", handlers.Search(*kindex, app.infoLog))

As you might see this is not the correct signature for the handler. It should have been passed without any arguments. i.e handlers.Search

How can I access kindex and infoLog from my Search handler?

func Search(c echo.Context, kindex string, infoLog *log.Logger) error {
  # Should I access a global variable from here?
  infoLog.Printf("Kendra Index: %v\n", kindex)
  # cut..
}
martins
  • 9,669
  • 11
  • 57
  • 85
  • 2
    You can use closures, i.e. functions that return an echo [`HandlerFunc`](https://godoc.org/github.com/labstack/echo#HandlerFunc), or you can use methods instead of functions. – mkopriva Aug 18 '20 at 08:12
  • @mkopriva I don't understand how that works. Would you please be so kind and give me an example? (I'm just starting to learn Go) :) – martins Aug 18 '20 at 08:24
  • 2
    Using [closure](https://play.golang.org/p/oz0n714UKEI), using [struct method](https://play.golang.org/p/3jX8kb9-N0P) – mkopriva Aug 18 '20 at 08:42
  • Perfect! Thanks for helping out!! :-D – martins Aug 18 '20 at 10:54

1 Answers1

5

You can create an anonymous function (closure) of given type and pass it to Echo:

    handler := func(c echo.Context) error {
      return Search(c, *kindex, infoLog)
    }
    e.GET("/search/:query", handler)
maxim_ge
  • 1,153
  • 1
  • 10
  • 18
  • Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users with similar issues. – FluffyKitten Aug 19 '20 at 01:39