【02-中介軟體】構建go web框架
【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
方法中。
現在,我們想要記錄每個請求的耗時:
請輸入程式碼