golang 從零實現一箇中間件(middleware)

實現中間件的背景

先看如下代碼

package main

func hello(wr http.ResponseWriter, r *http.Request) {
    wr.Write([]byte("hello"))
}

func main() {
    http.HandleFunc("/", hello)
    err := http.ListenAndServe(":8080", nil)
    ...
}

這是一個簡單的HTTP接口服務

現在有了一個新需求,需要在接口上增加服務的耗時處理日誌,我們對上面的程序進行少量修改

func hello(wr http.ResponseWriter, r *http.Request) {
    timeStart := time.Now()
    wr.Write([]byte("hello"))
    timeElapsed := time.Since(timeStart)
    fmt.Println(timeElapsed)
}

隨着業務的逐漸增多後,路由可能變成了

package main

func helloHandler(wr http.ResponseWriter, r *http.Request) {
    // ...
}

func showInfoHandler(wr http.ResponseWriter, r *http.Request) {
    // ...
}

func showEmailHandler(wr http.ResponseWriter, r *http.Request) {
    // ...
}

func showFriendsHandler(wr http.ResponseWriter, r *http.Request) {
    timeStart := time.Now()
    wr.Write([]byte("your friends is tom and alex"))
    timeElapsed := time.Since(timeStart)
    logger.Println(timeElapsed)
}

func main() {
    http.HandleFunc("/", helloHandler)
    http.HandleFunc("/info/show", showInfoHandler)
    http.HandleFunc("/email/show", showEmailHandler)
    http.HandleFunc("/friends/show", showFriendsHandler)
    // ...
}

此時,如果需要在每個路由上加一個參數信息日誌,我們會發現雖然代碼很好編寫,但是需要去所有的handle裏面修改這段代碼,並且以後新增的handle也需要了解並添加這段代碼。導致代碼維護起來越來越麻煩。因此我們需要使用中間件,將業務代碼和非業務代碼(例如上面的接口耗時統計,請求參數日誌等)拆分開

實現代碼

package main

import(
	"fmt"
	"net/http"
	"sync"
)


// HandlerFunc defines the handler used by  middleware as return value.
type HandlerFunc func(*Context)

// HandlersChain defines a HandlerFunc array.
type HandlersChain []HandlerFunc

//定義的上下文
type Context struct {
	Request   *http.Request
	Writer    http.ResponseWriter
	handlers HandlersChain
	index    int8

}

//模擬的調用堆棧
func (c *Context) Next() {
	c.index++
	for c.index < int8(len(c.handlers)) {
		//按順序執行HandlersChain內的函數
		//如果函數內無c.Next()方法調用則函數順序執行完
		//如果函數內有c.Next()方法調用則代碼執行到c.Next()方法處壓棧,等待後面的函數執行完在回來執行c.Next()後的命令
		c.handlers[c.index](c)
		c.index++
	}
}
func (c *Context) reset() {
	c.handlers = nil
	c.index = -1
}

//中間件組
type RouterGroup struct {
	//存儲定義的中間件
	Handlers HandlersChain
	engine   *Engine
}

func (group *RouterGroup) Use(middleware ...HandlerFunc) {
	group.Handlers = append(group.Handlers, middleware...)
}

func (group *RouterGroup) AddRoute(absolutePath string, handlers ...HandlerFunc) {
	handlers = group.combineHandlers(handlers)
	//建立路由和相關中間件組的綁定
	group.engine.addRoute(absolutePath, handlers)
}

//將定義的公用中間件和路由相關的中間件合併
func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {
	finalSize := len(group.Handlers) + len(handlers)
	mergedHandlers := make(HandlersChain, finalSize)
	copy(mergedHandlers, group.Handlers)
	copy(mergedHandlers[len(group.Handlers):], handlers)
	return mergedHandlers
}

type Engine struct{

	tree map[string]HandlersChain	// tree爲了簡化做成了map路由路徑完全匹配
	RouterGroup
	pool             sync.Pool		// 正常情況存在大量的上下文切換,所以使用一個臨時對象存儲
}

func NewEngine() *Engine {
	engine := &Engine{
		RouterGroup: RouterGroup{
			Handlers: nil,
		},
		tree: make(map[string]HandlersChain),
	}
	engine.RouterGroup.engine = engine
	engine.pool.New = func() interface{} {
		return engine.allocateContext()
	}
	return engine
}

func (engine *Engine) allocateContext() *Context {
	return &Context{}
}

//url請求時,默認執行入口
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	c := engine.pool.Get().(*Context)
	c.Writer = w
	c.Request = req
	c.reset()

	engine.handleHTTPRequest(c)

	engine.pool.Put(c)
}

func (engine *Engine) handleHTTPRequest(c *Context) {
	rPath := c.Request.URL.Path

	handlers := engine.getValue(rPath)
	if handlers != nil {
		c.handlers = handlers
		//按順序執行中間件
		c.Next()
		return
	}

}

//獲取路由下的相關HandlersChain
func (engine *Engine)getValue(path string)(handlers HandlersChain){
	handlers,ok := engine.tree[path]
	if !ok {
		return nil
	}
	return
}

func (engine *Engine) addRoute(path string, handlers HandlersChain) {
	engine.tree[path]=handlers
}

func (engine *Engine) Use(middleware ...HandlerFunc)  {
	engine.RouterGroup.Use(middleware...)
}

func main(){
	engine := NewEngine()
	engine.Use(func(c * Context){
		fmt.Println("begin middle1")
		fmt.Println("end middle1")
	})
	engine.Use(func(c * Context){
		fmt.Println("begin middle2")
		c.Next()
		fmt.Println("end middle2")
	})
	engine.Use(func(c * Context){
		fmt.Println("begin middle3")
		c.Next()
		fmt.Println("end middle3")
	})
	engine.AddRoute("/path1",func( c *Context){
		fmt.Println("path1")
		c.Writer.Write([]byte("path1"))

	})
	engine.AddRoute("/path2",func( c *Context){
		fmt.Println("path2")
		c.Writer.Write([]byte("path2"))

	})
	http.ListenAndServe(":8080", engine)
}

瀏覽器輸入:http://localhost:8080/path1

執行結果

執行結果的堆棧流程

應用場景

  • 對http的響應體進行壓縮處理
  • 設置一個特殊的路由,例如/ping,/healthcheck,用來給負載均衡一類的前置服務進行探活
  • 打印請求處理處理日誌,例如請求處理時間,請求路由
  • 從請求頭中讀取X-Forwarded-For和X-Real-IP,將http.Request中的RemoteAddr修改爲得到的RealIP
  • 爲本次請求生成單獨的requestid,可一路透傳,用來生成分佈式調用鏈路,也可用於在日誌中串連單次請求的所有邏輯
  • 用context.Timeout設置超時時間,並將其通過http.Request一路透傳下去
  • 通過定長大小的channel存儲token,並通過這些token對接口進行限流

參考資料

gin框架源碼中間價實現

GO高級編程

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章