dongyi0114
2016-06-25 06:20
浏览 506
已采纳

传递给http.HandleFunc的函数如何访问http.ResponseWriter和http.Request?

func main() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r http.Request) {
    // I never declared, initialized or passed w and r. How does this function get access to them?
}

图片转代码服务由CSDN问答提供 功能建议

  func main(){
 http.HandleFunc(“ /”,handler)
} \  n 
func handler(w http.ResponseWriter,r http.Request){
 //我从未声明,初始化或传递w和r。 此功能如何访问它们?
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doushenxu7294 2016-06-25 18:32
    已采纳

    http.HandleFunc knows its given input parms and that 2nd parm will have its own input parms (w http.ResponseWriter, r http.Request) ... so w and r are setup by http.HandleFunc which after it registers func handler as a callback it then invokes passing in w and r ... so responsibility is given to calling context not inside the callback definition itself

    Its a worth while exercise to write your own such pair of functions where one is a callback passed into and invoked by other function ... this pattern is orthogonal to golang and is a pervasive tool across languages

    已采纳该答案
    打赏 评论
  • duanhui5344 2016-06-25 06:24

    It's the magic of golang and the http package. No just kiding.

    In fact http.HandleFunc will do this for you, so when a request will reach your webservice with a matching url, then golang http package will call your handler with w and r ready to be used.

    打赏 评论

相关推荐 更多相似问题