I want to know what is happening here.
There is the interface for a http handler:
type Handler interface {
ServeHTTP(*Conn, *Request)
}
This implementation I think I understand.
type Counter int
func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) {
fmt.Fprintf(c, "counter = %d\n", ctr);
ctr++;
}
From my understanding it is that the type “Counter” implements the interface since it has a method that has the required signature. So far so good. Then this example is given:
func notFound(c *Conn, req *Request) {
c.SetHeader("Content-Type", "text/plain;", "charset=utf-8");
c.WriteHeader(StatusNotFound);
c.WriteString("404 page not found\n");
}
// Now we define a type to implement ServeHTTP:
type HandlerFunc func(*Conn, *Request)
func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) {
f(c, req) // the receiver's a func; call it
}
// Convert function to attach method, implement the interface:
var Handle404 = HandlerFunc(notFound);
Can somebody elaborate on why or how these various functions fit together?
This:
says that any type which satisfies the
Handlerinterface must have aServeHTTPmethod. The above would be inside the packagehttp.This puts a method on the Counter type which corresponds to ServeHTTP. This is an example which is separate from the following.
That’s right.
The following function by itself won’t work as a
Handler:The rest of this stuff is just fitting the above so that it can be a
Handler.In the following, a
HandlerFuncis a function which takes two arguments, pointer toConnand pointer toRequest, and returns nothing. In other words, any function which takes these arguments and returns nothing can be aHandlerFunc.Here
ServeHTTPis a method added to the typeHandlerFunc:All it does is to call the function itself (
f) with the arguments given.In the above line,
notFoundhas been finagled into being acceptable for the interface forHandlerby artificially creating a type instance out of the function itself and making the function into theServeHTTPmethod for the instance. NowHandle404can be used with theHandlerinterface. It’s basically a kind of trick.