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?
}
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
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.