我想知道这里发生了什么事.
有一个http处理程序的接口:
type Handler interface {
ServeHTTP(*Conn, *Request)
}
这个实现我想我理解.
type Counter int
func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) {
fmt.Fprintf(c, "counter = %d\n", ctr);
ctr++;
}
根据我的理解,"计数器"类型实现了接口,因为它有一个具有所需签名的方法.到目前一切尚好.然后给出此示例:
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);
有人能详细解释一下为什么或者如何将这些不同的功能结合在一起吗?