Writing a http.HandleFunc, why does this function work?

Take a look at my simple program below, could someone be kind enough explain this to me, please? When I call the indexHandler function, “http.HandleFunc(”/", indexHandler)", I don’t feed it parameters such as “indexHandle(a,b)” but yet the function definition needs two parameters “w” and “r” however it’s called without them and still works. Why?

package main

import (

func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, “Did it work?Hello World!”)

func main() {
http.HandleFunc("/", indexHandler)
http.ListenAndServe(":8000", nil)

You do not call the indexHandler at all, instead you pass it to http.HandleFunc, which then calls it. And in its signature it tells you, that the function passed to it must have the two parameters.

1 Like

That makes sense if I try and guess what a “signature” is using common sense, but for learning reasons, can I ask what is it’s a signature and where can I see it?

I tried “godoc net/http.HandleFunc” but just got an error.

Oh just found the documentation for this at " https://godoc.org/net/http#HandleFunc " so thought I would post to tell others. So how would you define what a signature is?

The signature of a function specifies its name (optional), its arguments and their types and the type of the return values.

So func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) is the signature of http.HandleFunc.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.