我试图理解:
该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
接口