我有下面的代码,它不像预期的那样工作。具体来说,对任何端点的所有请求都是作为对/banana/auth或/banana/description端点的请求处理的。
type Route struct {
AuthRoute string
DescriptionRoute string
}
var routes = [2]Route{
{
AuthRoute: "/apple/auth",
DescriptionRoute: "/apple/description",
},
{
AuthRoute: "/banana/auth",
DescriptionRoute: "/banana/description",
},
}
// ...
sm := http.NewServeMux()
for i, authServerConfig := range authServerConfigs {
authHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authServerConfig.Auth(w, r)
}
sm.Handle(routes[i].AuthRoute, authHandler)
descriptionHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authServerConfig.ServeDescription(w, r)
}
sm.Handle(routes[i].DescriptionRoute, descriptionHandler)
}
server := &http.Server{
// ...
Handler: sm,
// ...
}
server.ListenAndServe()当我继续用这些语句替换for-循环时,它完全符合我的要求:
authHandlerApple := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authServerConfig.Auth(w, r)
}
sm.Handle(routes[0].AuthRoute, authHandlerApple)
descriptionHandlerApple := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authServerConfig.ServeDescription(w, r)
}
sm.Handle(routes[0].DescriptionRoute, descriptionHandlerApple)
authHandlerBanana := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authServerConfig.Auth(w, r)
}
sm.Handle(routes[1].AuthRoute, authHandlerBanana)
descriptionHandlerBanana := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authServerConfig.ServeDescription(w, r)
}
sm.Handle(routes[1].DescriptionRoute, descriptionHandlerBanana)问题是,我最初做错了什么,如何避免像第二个示例那样编写笨重的代码?
发布于 2022-10-08 05:33:54
根据FAQ -当闭包作为goroutines运行时会发生什么?,每个闭包共享for循环中的单变量authServerConfig。要修复它,只需在循环中添加authServerConfig := authServerConfig即可。
for i, authServerConfig := range authServerConfigs {
authServerConfig := authServerConfig
authHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authServerConfig.Auth(w, r)
})
sm.Handle(routes[i].AuthRoute, authHandler)
descriptionHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authServerConfig.ServeDescription(w, r)
})
sm.Handle(routes[i].DescriptionRoute, descriptionHandler)
}https://stackoverflow.com/questions/73994039
复制相似问题