我希望你能帮助我,因为这让我很头疼。
我正在为之后执行的中间件创建一个链。但是看起来它已经反复出现了。匿名函数中的变量 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
}
我知道这是一个菜鸟问题,但我真诚地想了解导致此问题的原因以及如何解决这个问题。期待您的回答!
最佳答案
这似乎是循环问题中的闭包变量。您正在创建一个在每个循环中捕获 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 中间件处理程序通常不是这样工作的,因为它们通常相互包装而不是链接在一起。
关于覆盖变量时的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50010819/