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

报告相同问题?

悬赏问题

  • ¥15 速帮,学校需要在外上班没空
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义