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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.