darjun / blog-comments

博客评论
0 stars 0 forks source link

2021/07/13/in-post/godailylib/nethttp/ #28

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Go 每日一库之 net/http(基础和中间件) - 大俊的博客

简介 几乎所有的编程语言都以Hello World作为入门程序的示例,其中有一部分以编写一个 Web 服务器作为实战案例的开始。每种编程语言都有很多用于

https://darjun.github.io/2021/07/13/in-post/godailylib/nethttp/

whinc commented 1 year ago

文章写的真棒👍🏻

关于”中间必须先设置才能生效”的问题,除了重写 serverHTTP,还有一种简单的办法,只需要将楼主第一种方式稍微调整下,将 applyMiddlewares 放在闭包中延迟执行,如此任意地方调用 Use 中间件,在实际请求到达时中间件都已注册完毕,都会生效。

func (mux *MyMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
    // mux.ServeMux.Handle(pattern, applyMiddlewares(http.HandlerFunc(handler), mux.middlewares...))
    mux.ServeMux.Handle(pattern, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        h := applyMiddlewares(http.HandlerFunc(handler), mux.middlewares...)
        h.ServeHTTP(w, r)
    }))
}
darjun commented 1 year ago

嗯嗯,这种方式确实可以,棒

zhaofirst commented 1 year ago

牛逼

huangsir0 commented 1 year ago

Middleware 的返回值类型是http.Handler,为什么middlewares切片里能装Metric这种返回类型是http.HandlerFunc 的实例?小白求解

darjun commented 1 year ago

Middleware 的返回值类型是http.Handler,为什么middlewares切片里能装Metric这种返回类型是http.HandlerFunc 的实例?小白求解

http.HandlerFunc实现了http.Handler这个接口

cyj19 commented 1 year ago

其实根本不需要重写路由的Handle和HandleFunc方法,因为请求都会在ServeHTTP进入,在此处增加中间件即可。