【发布时间】:2020-10-01 12:22:54
【问题描述】:
我正在努力理解:
http.ServeMux 具有Handle 方法,用于注册新的http.Handler。
所以,你通过实现ServeHTTP(w http.ResponseWriter, r *http.Request)声明一个满足http.Handler接口的方法并注册它。
现在http.ListenAndServe(addr string, handler Handler) error 方法将处理程序作为它的第二个参数,这让我感到困惑,因为您将http.ServeMux 传递给它,它在调用m map[string]muxEntry 时将不同的处理程序类型作为属性m map[string]muxEntry 添加到*mux.Handle
例子
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有Handler属性,所以实现了接口?
【问题讨论】:
-
是的。
http.ServeMux本身就是一个处理程序。 -
http.ServeMux实现了Handler,因为它定义了一个匹配的ServeHTTP方法。