猿问

在 golang 中,使用 net/http 时如何调用带和不带尾括号的函数

在主函数中,我有一个 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()。如果我们没有明确提供,函数从哪里获取参数?这种调用函数的方式是什么?


谢谢你。


人到中年有点甜
浏览 206回答 2
2回答

四季花海

您不是从 main 中“调用”该函数,而是将其作为参数提供给HandleFunc,将其注册为在mux.Router.&nbsp;这种提供稍后调用的函数的模式通常称为“回调”。你的ParseSlash功能是类型http.HandlerFunctype&nbsp;HandlerFunc&nbsp;func(ResponseWriter,&nbsp;*Request)您的函数最终由http.Servervia 其ServeHTTP方法(此处为通过mux.Router)调用,并传递显示的参数。调用该函数时,http.ResponseWriter和*http.Request参数用于正在处理的单个 http 请求。

手掌心

这是一个简单的回调。当您想在将来调用某个函数时需要它,但现在您没有足够的信息来执行它。看 - http.ListenAndServe 创建一个服务器并等待客户端。您不能调用函数 ParseSlash,因为它在客户端连接并发送地址“/”之后才有意义。当它发生时,路由器将有足够的信息使用参数 http.ResponseWriter 和 *http.Request 调用您的代码。现在您应该了解闭包的工作原理 -&nbsp;https://tour.golang.org/moretypes/25。您将完成让我们返回 http 服务器https://www.nicolasmerouze.com/middlewares-golang-best-practices-examples/。
随时随地看视频慕课网APP

相关分类

Go
我要回答