使用范围为循环切片/地图注册多个路由 [英] Register multiple routes using range for loop slices/map

查看:22
本文介绍了使用范围为循环切片/地图注册多个路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

paths := []string{"/path0", "/path1", "/path2"/*... "/path-n"*/}//其中 n 是最后一条路径

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

for _, path := 范围路径{http.HandleFunc(路径,处理程序)}//在这种情况下,每个处理程序都打印到控制台或浏览器的路径

基本上提问者使用了这个代码:

for _, path := 范围路径{http.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {fmt.Fprintf(w, 路径)})}

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

但是如果我使用这个:

http.HandleFunc(paths[0], handler)http.HandleFunc(paths[1], handler)http.HandleFunc(paths[2], handler)//...http.HandleFunc(paths[n], handler)

输出正确.

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

你能给我提供完成这项任务的替代方法吗?

解决方案

所以问题是你实际上使用了这段代码:

for _, path := 范围路径{http.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {fmt.Fprintf(w, 路径)})}

您使用了一个函数字面量,一个闭包作为要注册的处理函数.闭包捕获它们引用的上下文,在你的例子中是 path 循环变量.

但是只有一个 path 循环变量,它的值在循环的每次迭代中都会被覆盖,并且它的最终值将是最后一个路径.规范中的相关部分:对于带有 range 子句的语句:><块引用>

迭代变量可以通过range"子句使用短变量声明 (:=).在这种情况下,它们的类型设置为各自迭代值的类型,并且它们的 scope 是块for"语句的;它们会在每次迭代中重复使用.如果迭代变量是在for"语句之外声明的,执行后它们的值将是最后一次迭代的值.

一旦 for 循环结束,并且您开始发出请求,每个注册的处理程序函数都会发回这个单个 path 变量的值.这就是为什么您会看到为所有请求的路径返回的最后一个路径.

解决方案很简单:在每次迭代中创建一个新变量,并在处理函数中使用它:

for _, path := 范围路径{路径 2 := 路径http.HandleFunc(path2, func(w http.ResponseWriter, req *http.Request) {fmt.Fprintf(w, path2)})}

这里发生的事情是我们在每次迭代中使用短变量声明来创建new 变量,用 path 循环变量的值初始化.而我们注册的处理函数将引用这个新变量,只对一个注册路径唯一.

另一个同样好的解决方案是使用带有参数的匿名函数来传递path 字符串.不过可能更难理解:

for _, path := 范围路径{功能(p字符串){http.HandleFunc(p, func(w http.ResponseWriter, req *http.Request) {fmt.Fprintf(w, p)})}(小路)}

这里发生的事情是我们调用一个匿名函数,将当前的 path 值传递给它,然后它注册处理函数,只使用这个匿名函数的参数(并且有一个新的,为每次调用分配不同的局部变量).

Consider I have slice of string paths:

paths := []string{"/path0", "/path1", "/path2" /*... "/path-n"*/ }
// where n is the last path

Using package net/http, I want to register handler for this path using for loop with range clause. This is how I do this:

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

EDIT: Basically the asker used this code:

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

But I ended up with same output which is the last element of slice, so when I go to /path1, the output is /path-n. Same behavior with other element, always print /path-n.

But if I use this:

http.HandleFunc(paths[0], handler)
http.HandleFunc(paths[1], handler)
http.HandleFunc(paths[2], handler)
// ...
http.HandleFunc(paths[n], handler)

The output is correct.

What's going on, did I miss something? I need for loop for registration given by slice of paths or map, so I can't do the second code.

Can you give me the alternative to accomplished this task?

解决方案

So the problem was that you actually used this code:

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

You used a function literal, a closure as the handler function to register. Closures capture the context they refer to, in your case the path loop variable.

But there is only a single path loop variable, its value is overwritten in each iterations of the loop, and its final value will be the last path. Relevant section from the spec: For statements with range clause:

The iteration variables may be declared by the "range" clause using a form of short variable declaration (:=). In this case their types are set to the types of the respective iteration values and their scope is the block of the "for" statement; they are re-used in each iteration. If the iteration variables are declared outside the "for" statement, after execution their values will be those of the last iteration.

Once the for loop is finished, and you start making requests, each registered handler function will send back the value of this single path variable. That's why you see the last path returned for all requested paths.

Solution is easy: create a new variable in each iteration, and use that in the handler function:

for _, path := range paths {
    path2 := path
    http.HandleFunc(path2, func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, path2)
    })
}

What happens here is that we use a short variable declaration in each iteration to create a new variable, initialized with the value of the path loop variable. And the handler function we register will refer to this new variable, unique only to one registered path.

Another, equally good solution is to use an anonymous function with a parameter to pass the path string. Might be harder to understand though:

for _, path := range paths {
    func(p string) {
        http.HandleFunc(p, func(w http.ResponseWriter, req *http.Request) {
            fmt.Fprintf(w, p)
        })
    }(path)
}

What happens here is that we call an anonymous function, passing the current path value to it, and it registers the handler function, using only the parameter of this anonymous function (and there's a new, distinct local variable allocated for each call).

这篇关于使用范围为循环切片/地图注册多个路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆