39

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

 4 years ago
source link: https://studygolang.com/articles/20358?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【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 方法中。

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

请输入代码

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK