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


(John Simmonds) #1

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 (
“fmt”
“net/http”
)

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


(Norbert Melzer) #2

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.


(John Simmonds) #3

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.


(John Simmonds) #4

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?


(Norbert Melzer) #5

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.