为什么 http.HandlerFunc 总是 returns 相同的随机数

Why http.HandlerFunc always returns the same random number

来自新手地鼠的问候!

我有以下 mux 路由器设置:

s.router.HandleFunc("/test", s.TestHandler())

s.TestHandler:

func (s *server) TestHandler() http.HandlerFunc {
    rnd := rand.Intn(100)
    response := struct {
        RND int `json:"rnd"`
    }{
        rnd,
    }
    return func(w http.ResponseWriter, r *http.Request) {
        s.respond(w, r, 200, response)
        return
    }
}

辅助方法s.respond:

func (s *server) respond(w http.ResponseWriter, r *http.Request, code int, data interface{}) {
    w.WriteHeader(code)
    if data != nil {
        json.NewEncoder(w).Encode(data)
    }
}

问题是当我发出 GET /test 时,除非重新启动应用程序,否则我会看到相同的数字。

我确定我做错了什么,如果有人指出我的错误,我将不胜感激。

Function literals

Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.


TestHandler() 生成一个 单个 随机值,然后 returns 一个 函数文字 ,即闭包,使用此已经生成的值在路由器执行时发送响应。

但是,闭包的外围函数不会,也没有理由在调用闭包时与闭包一起执行。周围的函数只有在它本身被调用时才会执行,例如当你在 s.router.HandleFunc("/test", s.TestHandler()) 中注册处理程序时。

因此,在提供的代码中,您的 TestHandler 中的 rand.Intn 函数只被调用一次,而不是像您似乎相信的那样,每次您使用请求。

要解决此问题,只需将生成随机值的代码移动到下一级:

func (s *server) TestHandler() http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        rnd := rand.Intn(100)
        response := struct {
            RND int `json:"rnd"`
        }{
            rnd,
        }

        s.respond(w, r, 200, response)
    }
}