之前有篇文章比較淺顯的分析了一下golang的服務器如何實現(xiàn),還有Handler, DefaultServeMux,HandlerFunc
的用處。
我們現(xiàn)在已經明白了DefaultServeMux
就是存放pattern
和handler
的地方,我們稱其為路由,那么我們可能會想,既然golang能夠實現(xiàn)這個路由,我們能否也模仿一個呢?
首先我們需要一個能夠保存客戶端的請求的一個容器(路由)。
創(chuàng)建路由結構體
type CopyRouter struct {
router map[string]map[string]http.HandlerFunc
}
在這里我們創(chuàng)建了一個像DefaultServeMux的路由。
客戶端請求存入路由
func (c *CopyRouter) HandleFunc(method, pattern string, handle http.HandlerFunc) {
if method == "" {
panic("Method can not be null!")
}
if pattern == "" {
panic("Pattern can not be null!")
}
if _, ok := c.router[method][pattern]; ok {
panic("Pattern Exists!")
}
if c.router == nil {
c.router = make(map[string]map[string]http.HandlerFunc)
}
if c.router[method] == nil {
c.router[method] = make(map[string]http.HandlerFunc)
}
c.router[method][pattern] = handle
}
這里我們模仿源碼中的ServeMux
將每一個URL所對應的handler保存起來。
實現(xiàn)Handler接口
func (c *CopyRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if f, ok := c.router[r.Method][r.URL.String()]; ok {
f.ServeHTTP(w, r)
}
}
在這里為什么要實現(xiàn)這個Handler接口,因為我們發(fā)現(xiàn)在ListenAndServe方法中,最后會調用h.ServeHTTP(w, r),
那么我們就只需要讓我們定義的路由實現(xiàn)Handler
接口就可以了。
獲取一個路由
func NewRouter() *CopyRouter {
return new(CopyRouter)
}
到這里,我們自己定義的路由就完成了,我們來看看使用方法。
func sayHi(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w,"Hi")
}
func main() {
copyRouter := copyrouter.NewRouter()
copyRouter.HandleFunc("GET","/sayHi", sayHi)
log.Fatal(http.ListenAndServe("localhost:8080", copyRouter))
}
這樣就完成了一個高仿版的自定義路由,是不是和golang提供給我們的ServeMux
很像,當然我們這個路由是一個低配版的,還有很多細節(jié)沒有處理。
現(xiàn)在再看看,我們的main函數(shù)里面的代碼不是很美觀,每一次都要寫get或者post方法,那么我們能否提供一個比較美觀的方式呢?可以,那么我們再封裝一下。
func (c *CopyRouter) GET(pattern string, handler http.HandlerFunc){
c.HandleFunc("GET", pattern, handler)
}
func (c *CopyRouter) POST(pattern string, handler http.HandlerFunc){
c.HandleFunc("POST", pattern, handler)
}
...
然后再修改一下調用方式。
copyRouter.GET("/sayHi",sayHi)
現(xiàn)在看起來是不是就美觀很多了?是的,很多web框架也是這樣,為什么用起來就感覺很流暢,因為這些大神們就是站在我們開發(fā)者的角度來考慮問題,提供了很方便的一些用法,封裝的很完善。
再考慮一下,我們這個自定義的路由還能做些什么,如果我們要記錄每一次的訪問請求,該如何處理呢?也很簡單,我們只需要將邏輯寫在ServeHTTP
方法中就可以了,稍微修改一下我們的代碼。
func (c *CopyRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if f, ok := c.router[r.Method][r.URL.String()]; ok {
func (handler http.Handler){
start := time.Now()
log.Printf(" 請求 [%s] 開始時間為 : %v\n", r.URL.String(), start)
f.ServeHTTP(w, r)
log.Printf(" 請求 [%s] 完成時間為 : %v\n", r.URL.String(), time.Since(start))
}(f)
}
}
這里我們又加入了一個記錄請求時間的功能,所以在這個自定義的路由里面還可以做更多的事情。
還有一點,就是我們在定義這個路由結構體的時候,能否將這個類型修改為Handler呢?也就是將這個類型map[string]map[string]http.HandlerFunc
修改為map[string]map[string]http.Handler
,是可以的,但是我們在調用的時候就需要在main方法里面做一下修改。
copyRouter.GET("/sayHi",HandlerFunc(sayHi))
在這里做一個強制轉換即可,但是這樣也不是很美觀。
看到這里,我們應該對一個源碼中的類型重點關注一下,那就是HandlerFunc。
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
這里HandlerFunc起到了一個適配器的作用,這是一個非常巧妙的設計,不得不說golang在接口這方面確實設計的很精妙。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- Golang極簡入門教程(一):基本概念
- Golang極簡入門教程(四):編寫第一個項目
- GO語言(golang)基礎知識
- golang利用不到20行代碼實現(xiàn)路由調度詳解