Go-net/http接口满意度
我试图理解:Go-net/http接口满意度,go,interface,Go,Interface,我试图理解: http.ServeMux具有用于注册新的http.Handler 因此,您可以通过实现ServeHTTP(w http.ResponseWriter,r*http.Request))来声明一个满足http.Handler接口的方法并注册它 现在,http.ListenAndServe(addr string,handler handler)错误方法将处理程序作为其第二个参数,这让我感到困惑,因为您将http.ServeMux传递给它,它在调用 范例 package main i
http.ServeMux
具有用于注册新的http.Handler
因此,您可以通过实现
ServeHTTP(w http.ResponseWriter,r*http.Request)
)来声明一个满足http.Handler
接口的方法并注册它
现在,http.ListenAndServe(addr string,handler handler)错误
方法将处理程序作为其第二个参数,这让我感到困惑,因为您将http.ServeMux
传递给它,它在调用
范例
package main
import (
"net/http"
"fmt"
)
type customHandler struct {
name string
}
func (c customHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is my first middleware in Go")
}
func main() {
router := http.NewServeMux()
customH := customHandler{"this is a test"}
router.Handle("/", customH)
http.ListenAndServe(":8080", router)
}
我的问题是这是如何工作的?因为
http.ServeMux
有处理程序属性,所以它实现了接口吗?http.ServeMux
方法,因此它满足http.Handler
接口是http.ServeMux
本身就是一个处理程序。http.ServeMux
实现handler
,因为它定义了一个匹配的ServeHTTP
方法。