HandleFunc调用错误的处理程序

时间:2019-07-13 19:44:02

标签: go httpserver

这是我的代码:

package main

import (
    "net/http"
    "log"
    "fmt"
)

func main() {
    server := &http.Server{Addr: ":8080"}

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/plain")
        fmt.Fprintf(w, "generic handler")
    })

    modules := []string{"/one/", "/two/"}
    for index, item := range modules {
        http.HandleFunc(item, func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set("Content-Type", "text/plain")
            fmt.Fprintf(w, "handler %d \"%s\"", index, item)
        })
    }

    if err := server.ListenAndServe(); err != nil {
        if err != http.ErrServerClosed {
            log.Fatal(err)
        }
    }
}

如您所见,我为子树//one//two/注册了三个处理程序。当我运行此代码时,会看到以下行为:

$ curl http://localhost:8080/
generic handler⏎
$ curl http://localhost:8080/two/
handler 1 "/two/"⏎
$ curl http://localhost:8080/one/
handler 1 "/two/"⏎

因此由于某种原因,查询路径/one/会调用/two/的处理函数。为什么会发生这种情况?

0 个答案:

没有答案