我想知道这里发生了什么.
有一个http处理程序的接口:
type Handler interface {
ServeHTTP(*Conn, *Request)
}
Run Code Online (Sandbox Code Playgroud)
这个实现我想我明白了.
type Counter int
func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) {
fmt.Fprintf(c, "counter = %d\n", ctr);
ctr++;
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,"Counter"类型实现了接口,因为它有一个具有所需签名的方法.到现在为止还挺好.然后给出了这个例子:
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 …Run Code Online (Sandbox Code Playgroud) go ×1