在 main 函数中,我有一个 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 中,我们不是将函数调用为 ParseSlash()
,而是在 router.HandleFunc()
中调用 ParseSlash
。如果我们没有明确提供,函数从哪里获取参数?这种调用函数的方式是什么?
谢谢。
最佳答案
您不是从 main“调用”函数,而是将其作为参数提供给 HandleFunc
,将其注册为在 mux.Router 中为路径“/”调用
。这种提供稍后调用的函数的模式通常称为“回调”。
您的 ParseSlash
函数的类型是 http.HandlerFunc
type HandlerFunc func(ResponseWriter, *Request)
您的函数最终由 http.Server
通过其 ServeHTTP
方法调用(此处通过 mux.Router
),传递显示的参数。调用该函数时,http.ResponseWriter
和 *http.Request
参数用于正在处理的单个 http 请求。
关于function - 在 golang 中,使用 net/http 时如何调用带和不带尾随括号的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37793000/