Go中间件
定義
中間件(英語:Middleware),又譯中間件,
是提供系統軟件和應用軟件(網路系統與自己的代碼之間的信息交換)之間連接的軟件,以便于軟件各部件之間的溝通,特別是應用軟件對于系統軟件的集中的邏輯,在現代信息技術應用框架如Web服務、面向服務的體系結構等中應用比較廣泛。
通俗講解:
有時候我們需要統計web service接口的數據,
比如記錄日志、統計API調用時間、或者對HandleFunc進行錯誤處理,這個時候,middleware就很有幫助。
英文:Middleware in Webservice?
If you have some code that needs to be run for some common requests, you need some way to stack on top of each other and run them in sequence. This problem is solved elegantly through middleware packages.?
實現
實現方法
中間件是在handles與入口文件之間的部分,起到驗證參數權限認證的作用
handles是在middleware之前的?
handles是負責處理http的頭部與內容的
middleware是負責處理把路由與身份校驗權限啊等等的
Implement our middleware so that it satisfies the http.Handler interface.(使我們的中間件能搞滿足 http.handlers 這個接口)
Build up a chain of handlers containing both our middleware handler and our normal application handler, which we can register with a http.ServeMux.(建立一個 handlers 鏈,使其能夠滿足中間件的 handler 和 正常應用的 handler,并且能夠注冊到 http.ServeMux)
概念定義
ServeMux?
A ServeMux is essentially a HTTP request router (or multiplexor). It compares incoming requests against a list of predefined URL paths, and calls the associated handler for the path whenever a match is found.
(ServeMux本質上是HTTP請求路由器(或多路復用器)。 它將傳入的請求與預定義的URL路徑列表進行比較,并在找到匹配項時調用路徑的關聯處理程序)
Handlers?
Handlers are responsible for writing response headers and bodies. Almost any object can be a handler, so long as it satisfies the http.Handler interface.
(處理程序負責編寫響應頭和主體。 幾乎任何對象都可以是處理程序,只要它滿足http.Handler接口即可)
例子
package mainimport ("log""math/rand""net/http""time")// Compute is compute process for doing task func Compute(w http.ResponseWriter, r *http.Request) {time.Sleep(time.Duration((500 + rand.Intn(500))) * time.Millisecond)w.Write([]byte("finish")) }// Version is getting version task func Version(w http.ResponseWriter, r *http.Request) {time.Sleep(time.Duration((10 + rand.Intn(50))) * time.Millisecond)w.Write([]byte("version")) }func middleware(fn func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {return func(w http.ResponseWriter, r *http.Request) {begin := time.Now()defer func() {log.Printf("time_used: %v", time.Now().Sub(begin))}()// logginglog.Printf(r.RequestURI)fn(w, r)} }func main() {http.HandleFunc("/compute", middleware(Compute))http.HandleFunc("/version", middleware(Version))log.Panic(http.ListenAndServe(":8080", nil)) } curl http://localhost:8080/compute # 2017/12/13 16:57:15 [GET] /compute, time_used: 583.357048mscurl http://localhost:8080/version # 2017/12/13 16:57:24 [GET] /version, time_used: 47.09209ms 此處的middlehandle相當于相同代碼的提取例子
package mainimport ("log""net/http" )func middlewareOne(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {log.Println("Executing middlewareOne")next.ServeHTTP(w, r)log.Println("Executing middlewareOne again")}) }func middlewareTwo(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {log.Println("Executing middlewareTwo")if r.URL.Path != "/" {return}next.ServeHTTP(w, r)log.Println("Executing middlewareTwo again")}) }func final(w http.ResponseWriter, r *http.Request) {log.Println("Executing finalHandler")w.Write([]byte("OK")) }func main() {finalHandler := http.HandlerFunc(final)http.Handle("/", middlewareOne(middlewareTwo(finalHandler)))http.ListenAndServe(":8080", nil) } 瀏覽器訪問:http://localhost:8080/ 結果: 2018/02/01 13:04:48 Executing middlewareOne 2018/02/01 13:04:48 Executing middlewareTwo 2018/02/01 13:04:48 Executing finalHandler 2018/02/01 13:04:48 Executing middlewareTwo again 2018/02/01 13:04:48 Executing middlewareOne again?
總結
- 上一篇: 情商为什么情商比智商更重要?
- 下一篇: 一寸、两寸、三寸照片尺寸是多少?