-1

I am trying to create middleware inside routes and wondering how one can get the values of arguments passed inside a func() argument.

For example:

func (c appContainer) Get(path string, fn func(rw http.ResponseWriter, req *http.Request)) {

    // HOW DO I GET THE VALUES OF rw AND req PASSED IN fn func()?

    c.providers[ROUTER].(Routable).Get(path, fn)
}

I looked through the reflection docs but it's not clear to me or perhaps there is a simpler way?

EDITED (SOLUTION)

It turns out reflection is not needed, as suggested by Adam in his response to this post, as well as Jason on his golang-nuts reply to my question.

The idea is to create a new anonymous function which then intercepts the parameters passed to it for modification/enhancement before calling the original function.

This is what I ended up doing and it worked like a charm, which I am posting in case it helps someone else:

type handlerFn func(rw http.ResponseWriter, req *http.Request)

func (c appContainer) Get(path string, fn handlerFn) {
    nfn := func(rw http.ResponseWriter, req *http.Request) {
        c.providers[LOGGER].(Loggable).Info("[%s] %s", req.Method, req.URL.Path)
        fn(rw, req)
    }
    c.providers[ROUTER].(Routable).Get(path, nfn)
}
Ricardo Rossi
  • 524
  • 5
  • 13

1 Answers1

3

simple answer: you don't. Not at that place at least

the variables rw and req make first sense if the function fn is called. (or a function that calls fn, which probably will have rw and req variables)

In your case it is probably where appContainer uses the routes configured

To better understand how middleware concept works a simple example can be found here: https://golang.org/doc/articles/wiki/

you might want to scroll down to "Introducing Function Literals and Closures"

Adam Vincze
  • 861
  • 6
  • 8
  • Good answer. I'd also suggest the OP look at https://justinas.org/writing-http-middleware-in-go/ and http://www.alexedwards.net/blog/making-and-using-middleware - it looks like they're currently working against the grain. If you have to reach to `reflect` just to write HTTP middleware something might be askew! – elithrar Jul 02 '15 at 05:35
  • Thanks for your response Adam! I edited my original question to show how I ended up implementing it. – Ricardo Rossi Jul 02 '15 at 15:44