首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在循环中向ServeMux声明和分配处理程序不起作用。

在循环中向ServeMux声明和分配处理程序不起作用。
EN

Stack Overflow用户
提问于 2022-10-08 02:50:18
回答 1查看 37关注 0票数 0

我有下面的代码,它不像预期的那样工作。具体来说,对任何端点的所有请求都是作为对/banana/auth/banana/description端点的请求处理的。

代码语言:javascript
复制
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-循环时,它完全符合我的要求:

代码语言:javascript
复制
    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)

问题是,我最初做错了什么,如何避免像第二个示例那样编写笨重的代码?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-08 05:33:54

根据FAQ -当闭包作为goroutines运行时会发生什么?,每个闭包共享for循环中的单变量authServerConfig。要修复它,只需在循环中添加authServerConfig := authServerConfig即可。

代码语言:javascript
复制
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)
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73994039

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档