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

标签 function http go parameters

在 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/

相关文章:

javascript - 函数命名和启动

c - C 中的指针和函数歧义

c - 在 C 中创建一个 StartsWith 函数,得到 "Segmentation fault",有什么问题吗?

来自外部数据源的 "no data available"的 HTTP 状态代码

json - 使用 "embedded"键将 JSON 解码为结构

http - 使用 rs.cors 时返回 http 状态码

c - 使用指针函数的程序方差和标准差

c# - 编码我的字符串以通过 C# 发送 http 请求

javascript - 我如何使用可请求扩展的 Bluebird promise ?

google-app-engine - Cloud Datastore 客户端库与 App Engine Go Standard 上的 App Engine SDK