5

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
billyzaelani
  • 567
  • 1
  • 5
  • 18
  • 2
    Based on what you wrote, it should work with the loop too. Please provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Most likely there is an error in your code which you didn't show us. – icza May 18 '17 at 09:54
  • @icza still encounter the problem, take a look at this code https://play.golang.org/p/KfeXAW8cSe. It didn't work in playground, if don't mind try this at your console and see the result. – billyzaelani May 18 '17 at 10:08

1 Answers1

11

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).

icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    It works, thanks in advance. New to me that the variable `path` is simply overwriten so the last `path` will be printout. Before this i think `path` is created every iteration and live in different scope each itteration. – billyzaelani May 18 '17 at 10:23
  • 1
    hey! Here just to say I found this comment after 4-5 hours struggling (dying inside actually)....Thanks :,) – edoardottt Apr 10 '22 at 16:06