我想知道这里发生了什么.
有一个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 method, implement the interface:
var Handle404 = HandlerFunc(notFound);
Run Code Online (Sandbox Code Playgroud)
有人可以详细说明这些不同功能为何或如何结合在一起?
小智 14
这个:
type Handler interface {
ServeHTTP(*Conn, *Request)
}
Run Code Online (Sandbox Code Playgroud)
说任何满足Handler接口的类型都必须有一个ServeHTTP方法.以上内容将在包内http.
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类型上,该方法对应于ServeHTTP.这是一个与以下内容分开的示例.
根据我的理解,"Counter"类型实现了接口,因为它有一个具有所需签名的方法.
那就对了.
以下函数本身不能用作Handler:
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");
}
Run Code Online (Sandbox Code Playgroud)
剩下的这些东西恰好适合上面所以它可以是一个Handler.
在下面,a HandlerFunc是一个函数,它接受两个参数,指向指针Conn和指针Request,并且不返回任何内容.换句话说,任何接受这些参数并且不返回任何内容的函数都可以是a HandlerFunc.
// Now we define a type to implement ServeHTTP:
type HandlerFunc func(*Conn, *Request)
Run Code Online (Sandbox Code Playgroud)
这ServeHTTP是添加到类型的方法HandlerFunc:
func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) {
f(c, req) // the receiver's a func; call it
}
Run Code Online (Sandbox Code Playgroud)
它所做的就是f用给定的参数调用函数本身().
// Convert function to attach method, implement the interface:
var Handle404 = HandlerFunc(notFound);
Run Code Online (Sandbox Code Playgroud)
在上面的行中,通过人工创建函数本身的类型实例并将函数转换为实例的方法,notFound已经被指定为可接受的接口.现在可以与界面一起使用.这基本上是一种技巧.HandlerServeHTTPHandle404Handler