在主函数中,我有一个 gorilla mux 路由器,以及一个处理路由的函数。var router = mux.NewRouter()func main() { router.HandleFunc("/", ParseSlash) http.Handle("/", router) http.ListenAndServe(":8000", nil)}ParseSlash 看起来像const slash = `<h1>Login</h1><form method="post" action="/login"> <label for="name">User name</label> <input type="text" id="name" name="name"> <label for="password">Password</label> <input type="password" id="password" name="password"> <button type="submit">Login</button></form>`func ParseSlash(response http.ResponseWriter, request *http.Request) { fmt.Fprintf(response, slash)}但是,在 main 中,我们不是调用函数 as ParseSlash(),而是调用ParseSlashinside router.HandleFunc()。如果我们没有明确提供,函数从哪里获取参数?这种调用函数的方式是什么?谢谢你。
2 回答

四季花海
TA贡献1811条经验 获得超5个赞
您不是从 main 中“调用”该函数,而是将其作为参数提供给HandleFunc
,将其注册为在mux.Router
. 这种提供稍后调用的函数的模式通常称为“回调”。
你的ParseSlash
功能是类型http.HandlerFunc
type HandlerFunc func(ResponseWriter, *Request)
您的函数最终由http.Server
via 其ServeHTTP
方法(此处为通过mux.Router
)调用,并传递显示的参数。调用该函数时,http.ResponseWriter
和*http.Request
参数用于正在处理的单个 http 请求。

手掌心
TA贡献1942条经验 获得超3个赞
这是一个简单的回调。当您想在将来调用某个函数时需要它,但现在您没有足够的信息来执行它。看 - http.ListenAndServe 创建一个服务器并等待客户端。
您不能调用函数 ParseSlash,因为它在客户端连接并发送地址“/”之后才有意义。当它发生时,路由器将有足够的信息使用参数 http.ResponseWriter 和 *http.Request 调用您的代码。
现在您应该了解闭包的工作原理 - https://tour.golang.org/moretypes/25。您将完成让我们返回 http 服务器https://www.nicolasmerouze.com/middlewares-golang-best-practices-examples/。
- 2 回答
- 0 关注
- 205 浏览
添加回答
举报
0/150
提交
取消