相关疑难解决方法(0)

Golang:使用环路切片/贴图的范围注册多个路线

考虑我有一些字符串路径:

paths := []string{"/path0", "/path1", "/path2" /*... "/path-n"*/ }
// where n is the last path
Run Code Online (Sandbox Code Playgroud)

使用包net/http,我想使用for带有range子句的循环注册此路径的处理程序.这就是我这样做的方式:

for _, path := range paths {
    http.HandleFunc(path, handler)
}
// in this case every handler is print the path to the console or to the browser
Run Code Online (Sandbox Code Playgroud)

但我最终得到了相同的输出,这是切片的最后一个元素,所以当我去/path1,输出是/path-n.与其他元素的行为相同,始终打印/path-n.

但如果我用这个:

for _, path := range paths {
    http.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, path)
    })
}
Run Code Online (Sandbox Code Playgroud)

输出是正确的.

发生了什么事,我错过了什么吗?我需要for通过切片路径或地图给出的循环注册,所以我不能做第二个代码.

你能给我替代完成这项任务吗?

routing closures for-loop go slice

1
推荐指数
1
解决办法
1004
查看次数

如何在Golang中将[] * Cookie转换为[] Cookie

我有[] * Cookie数组,但是如何获取[] Cookie数组?我尝试使用*符号,但是出现语法错误。

go

0
推荐指数
1
解决办法
67
查看次数

标签 统计

go ×2

closures ×1

for-loop ×1

routing ×1

slice ×1