【问题标题】:Go net/http interface satisfactiongo net/http接口满意
【发布时间】: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 方法。

标签: go interface


【解决方案1】:

http.ServeMuximplementhttp.ServeHTTP方法,因此它满足http.Handler接口

【讨论】:

    猜你喜欢
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 2014-11-19
    • 1970-01-01
    • 2021-04-10
    • 2010-12-18
    • 2013-05-02
    相关资源
    最近更新 更多