doujiu7704 2016-06-13 14:56
浏览 126
已采纳

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

In the main function, I have a gorilla mux router, and a function to handle the route.

var router = mux.NewRouter()
func main() {   
    router.HandleFunc("/", ParseSlash)
    http.Handle("/", router)
    http.ListenAndServe(":8000", nil)
}

and ParseSlash looks like

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)
}

However, in main, we are not calling the function as ParseSlash(), but ParseSlash inside router.HandleFunc(). Where do the function get the parameters from, if we are not providing explicitely? What is this way of calling a function termed as?

Thank you.

  • 写回答

2条回答 默认 最新

  • dsavz66262 2016-06-13 14:59
    关注

    You are not "calling" the function from main, you are providing it as a argument to HandleFunc, registering it to be called for the path "/" in the mux.Router. This pattern of providing a function to be called later is typically known as a "callback".

    Your ParseSlash function is of the type http.HandlerFunc

    type HandlerFunc func(ResponseWriter, *Request)
    

    Your function is eventually called by the http.Server via its ServeHTTP method (here, via the mux.Router), passing the arguments shown. When the function is called, the http.ResponseWriter and *http.Request arguments are for the individual http request being handled.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效