我有以下代碼,但它沒有按預期作業。具體來說,對任何端點的所有請求都作為對一個/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)
問題是,我最初做錯了什么,如何避免撰寫第二個示例中的笨拙代碼?
uj5u.com熱心網友回復:
每個常見問題解答 - 作為 goroutines 運行的閉包會發生什么authServerConfig ,每個閉包在for回圈中共享該單個變數。要修復它,只需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://www.uj5u.com/shujuku/512003.html
標籤:http去服务复用器
上一篇:SQL抽象語法樹及改寫場景應用
