我正在嘗試在路由中創建中間件,并想知道如何獲取在 func() 參數中傳遞的參數的值。例如: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)}我查看了反射文檔,但我不清楚,或者有更簡單的方法?已編輯(解決方案)事實證明,正如亞當在他對這篇文章的回應中所建議的那樣,以及杰森在他對我的問題的golang-nuts 答復中所建議的那樣,反思是不需要的。這個想法是創建一個新的匿名函數,然后在調用原始函數之前攔截傳遞給它的參數以進行修改/增強。這就是我最終做的事情,它就像一個魅力,我發布它以防它幫助其他人: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 回答
- 0 關注
- 270 瀏覽
添加回答
舉報
0/150
提交
取消
