英文:
Golang: Gin router with map is picking only one handler
问题
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
server := gin.Default()
funcs := map[string]func(string){
"func2": func2,
"func1": func1,
}
for k, v := range funcs {
server.GET(k, func(ctx *gin.Context) {
v(k)
})
}
server.Run("127.0.0.1:8879")
}
func func1(name string) {
fmt.Println("func1", name)
}
func func2(name string) {
fmt.Println("func2", name)
}
请考虑这段代码,这里我有一个函数映射表。现在当在gin路由器中运行时,
[GIN-debug] GET /func2 --> main.main.func1 (3 handlers)
[GIN-debug] GET /func1 --> main.main.func1 (3 handlers)
现在,无论我使用func1还是func2发起请求,我只会调用一个函数。有什么想法,为什么会发生这种情况,如何修复?
注意:我必须将映射表中的键传递给函数。
英文:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
server := gin.Default()
funcs := map[string]func(string){
"func2": func2,
"func1": func1,
}
for k, v := range funcs {
server.GET(k, func(ctx *gin.Context) {
v(k)
})
}
server.Run("127.0.0.1:8879")
}
func func1(name string) {
fmt.Println("func1", name)
}
func func2(name string) {
fmt.Println("func2", name)
}
Please consider this code, here I have a map to functions. Now when running this is gin router.
[GIN-debug] GET /func2 --> main.main.func1 (3 handlers)
[GIN-debug] GET /func1 --> main.main.func1 (3 handlers)
Now, no matter if is make request with func1 for func2, I am only getting one function called. Any idea, why this happening and how to fix this.
>Note: I have to pass the key from map to func
答案1
得分: 4
循环变量在每次迭代时被覆盖,所以所有的处理程序都使用最后一次迭代的 v
和 k
的副本。你可以通过创建副本来解决这个问题:
for k, v := range funcs {
kCopy := k
vCopy := v
server.GET(k, func(ctx *gin.Context) {
vCopy(kCopy)
})
}
英文:
Loop variables are overwritten at each iteration, so all handlers are using the last copy of v
and k
. You can fix by creating copies:
for k, v := range funcs {
k:=k
v:=v
server.GET(k, func(ctx *gin.Context) {
v(k)
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论