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
方法。