去网络/http接口满意度



我试图理解:

http.ServeMux具有用于注册新http.Handler的句柄方法。
因此,您通过实现ServeHTTP(w http.ResponseWriter, r *http.Request)) 来声明一个满足http.Handler接口的方法并注册它。

现在http.ListenAndServe(addr string, handler Handler) error方法将处理程序作为其第二个参数,这让我感到困惑,因为您向它传递了http.ServeMux,该将不同的处理程序类型作为属性m map[string]muxEntry调用 *mux 期间添加。处理

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.ServeHTTP方法,因此它满足http.Handler接口

最新更新