覆盖变量

时间:2018-04-24 21:15:57

标签: recursion go

我希望你能帮助我,因为这让我很头疼。

我为之后执行的中间件创建了一个链。但看起来它已经反复出现。匿名函数中的变量next指向自身。

type MiddlewareInterface interface {
    // Run the middleware for the given request, and receive the next handler.
    Run(http.ResponseWriter, *http.Request, http.Handler)
}

createChain(collection []MiddlewareInterface, handler http.Handler) http.Handler
    next := handler

    for _, middlew := range collection {
        next = func(w http.ResponseWriter, res *http.Request) {
            middlew.Run(w, res, next)
        }
    }

    return next
}

我知道这是一个菜鸟问题,但我真心希望了解导致这种情况的原因以及如何解决这个问题。期待您的回答!

1 个答案:

答案 0 :(得分:3)

似乎这是循环问题中的闭包变量。您正在创建一个在每个循环中捕获next的函数,但这意味着所有函数共享相同的变量next并且它们都将具有最后一个的值环。我想你可以通过在循环范围内引入一个新的临时变量来修复它:

func createChain(collection []MiddlewareInterface, handler http.Handler) http.Handler
    next := handler

    for _, middlew := range collection {
        thisNext:= next
        mw := middlew
        next = func(w http.ResponseWriter, res *http.Request) {
            mw.Run(w, res, thisNext)
        }
    }

    return next
}

新变量定义的放置可能不太正确,但关闭问题肯定会成为问题的根源。通常,http中间件处理程序的工作方式并不常见,因为它们通常相互包装而不是被链接。