concept handler function in category go

This is an excerpt from Manning's book Go Web Programming.
This is followed by a function definition. You define a function named handler. The term handler is often used for callback functions triggered by an event, and that’s what it’s used for here (though technically, at least in Go, this isn’t a handler but a handler function—we’ll explore this in chapter 3).
func handler(writer http.ResponseWriter, request *http.Request) { fmt.Fprintf(writer, "Hello World, %s!", request.URL.Path[1:]) }The handler function has two input parameters—a ResponseWriter interface and a pointer to a Request struct. It takes information from the Request to create an HTTP response, which is sent out through the ResponseWriter. The Fprintf function is called with the ResponseWriter, a format string with a single string format specifier (%s), followed by the path information extracted from the Request. Because you went to the address http://localhost:8080, there’s no path information and so nothing is printed out. If you’d gone to the address http://localhost:8080/sausheong/was/here, figure 1.4 shows how it would’ve looked in the browser.
We talked about handlers, but what are handler functions? Handler functions are functions that behave like handlers. Handler functions have the same signature as the ServeHTTP method; that is, they accept a ResponseWriter and a pointer to a Request. The following listing shows how this works with our server.
Listing 3.8. Handling requests with handler functions
package main import ( "fmt" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello!") } func world(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "World!") } func main() { server := http.Server{ Addr: "127.0.0.1:8080", } http.HandleFunc("/hello", hello) http.HandleFunc("/world", world) server.ListenAndServe() }
You might have noticed that while I mentioned earlier that we’re chaining handlers, the code in listing 3.10 actually shows chaining handler functions. The mechanisms for both chaining handlers and handler functions are very similar, as shown next.
Instead of returning an anonymous function, now we adapt that anonymous function using HandlerFunc, which, if you remember from earlier, returns a Handler. Also, instead of executing the handler function, we now take the handler and call its ServeHTTP function. Everything else remains mostly the same, except that instead of registering a handler function, we register the handler:
hello := HelloHandler{} http.Handle("/hello", protect(log(hello)))Chaining handlers or handler functions is a common idiom you’ll find in many web application frameworks.