dqh1992 2015-07-02 03:43
浏览 1551
已采纳

如何获取在GO中的func()参数内传递的参数值?

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)
}
  • 写回答

1条回答 默认 最新

  • drpsrvu85668 2015-07-02 05:20
    关注

    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"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?