首页 > 解决方案 > 覆盖变量时的递归

问题描述

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

我正在为之后执行的中间件创建一个链。但它似乎已经变得反复出现。匿名函数中的变量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
}

我知道这是一个菜鸟问题,但我真诚地想了解是什么原因造成的,以及如何解决这个问题。期待您的回答!

标签: recursiongo

解决方案


似乎这是循环问题中的闭包变量。您正在创建一个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 中间件处理程序通常不是如何工作的,因为它们通常相互包装而不是被链接。


推荐阅读