【02-中间件】构建go web框架

之前我们项目中遇到的问题是代码重复。在处理请求之前,我们通常需要进行日志记录,异常捕获,用户认证等操作。并且这些操作需要被应用到每一个处理handler中。

开始之前回顾一下之前的项目

使用golang的基础包net/http创建了一个非常简单的应用

import "net/http"type DefaultHandler struct {}func (DefaultHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)  {    path := r.URL.Path    _, _ = w.Write([]byte(path + "  wellcome to http server."))}func userLogin(w http.ResponseWriter, r *http.Request)  {    path := r.URL.Path    _, _ = w.Write([]byte(path + "  wellcome to http server by handleFunc."))}func main() {    http.Handle("/", DefaultHandler{})    http.HandleFunc("/apis", userLogin)    _ = http.ListenAndServe("0.0.0.0:8080", nil)}

http.Handle 接受两个参数,第二个参数类型是http.Handler, 它是一个接口类型包含了ServeHTTP(ResponseWriter, *Request)方法,所以任何实现了该方法的类型,都可以当作http.Handler来使用,传入http.Handle 方法中。

现在,我们想要记录每个请求的耗时:

请输入代码