## HTTP路由
HTTP路由組件負責將HTTP請求交到對應的函數處理(或者是一個struct的方法),如前面小節所描述的結構圖,路由在框架中相當于一個事件處理器,而這個事件包括:
* 用戶請求的路徑(path)(例如:/user/123,/article/123),當然還有查詢串信息(例如?id=11)
* HTTP的請求方法(method)(GET、POST、PUT、DELETE、PATCH等)
路由器就是根據用戶請求的事件信息轉發到相應的處理函數(控制層)。
## [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/13.2.md#默認的路由實現)默認的路由實現
在3.4小節有過介紹Go的http包的詳解,里面介紹了Go的http包如何設計和實現路由,這里繼續以一個例子來說明:
~~~
func fooHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}
http.HandleFunc("/foo", fooHandler)
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
~~~
上面的例子調用了http默認的DefaultServeMux來添加路由,需要提供兩個參數,第一個參數是希望用戶訪問此資源的URL路徑(保存在r.URL.Path),第二參數是即將要執行的函數,以提供用戶訪問的資源。路由的思路主要集中在兩點:
* 添加路由信息
* 根據用戶請求轉發到要執行的函數
Go默認的路由添加是通過函數`http.Handle`和`http.HandleFunc`等來添加,底層都是調用了`DefaultServeMux.Handle(pattern string, handler Handler)`,這個函數會把路由信息存儲在一個map信息中`map[string]muxEntry`,這就解決了上面說的第一點。
Go監聽端口,然后接收到tcp連接會扔給Handler來處理,上面的例子默認nil即為`http.DefaultServeMux`,通過`DefaultServeMux.ServeHTTP`函數來進行調度,遍歷之前存儲的map路由信息,和用戶訪問的URL進行匹配,以查詢對應注冊的處理函數,這樣就實現了上面所說的第二點。
~~~
for k, v := range mux.m {
if !pathMatch(k, path) {
continue
}
if h == nil || len(k) > n {
n = len(k)
h = v.h
}
}
~~~
## [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/13.2.md#beego框架路由實現)beego框架路由實現
目前幾乎所有的Web應用路由實現都是基于http默認的路由器,但是Go自帶的路由器有幾個限制:
* 不支持參數設定,例如/user/:uid 這種泛類型匹配
* 無法很好的支持REST模式,無法限制訪問的方法,例如上面的例子中,用戶訪問/foo,可以用GET、POST、DELETE、HEAD等方式訪問
* 一般網站的路由規則太多了,編寫繁瑣。我前面自己開發了一個API應用,路由規則有三十幾條,這種路由多了之后其實可以進一步簡化,通過struct的方法進行一種簡化
beego框架的路由器基于上面的幾點限制考慮設計了一種REST方式的路由實現,路由設計也是基于上面Go默認設計的兩點來考慮:存儲路由和轉發路由
### [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/13.2.md#存儲路由)存儲路由
針對前面所說的限制點,我們首先要解決參數支持就需要用到正則,第二和第三點我們通過一種變通的方法來解決,REST的方法對應到struct的方法中去,然后路由到struct而不是函數,這樣在轉發路由的時候就可以根據method來執行不同的方法。
根據上面的思路,我們設計了兩個數據類型controllerInfo(保存路徑和對應的struct,這里是一個reflect.Type類型)和ControllerRegistor(routers是一個slice用來保存用戶添加的路由信息,以及beego框架的應用信息)
~~~
type controllerInfo struct {
regex *regexp.Regexp
params map[int]string
controllerType reflect.Type
}
type ControllerRegistor struct {
routers []*controllerInfo
Application *App
}
~~~
ControllerRegistor對外的接口函數有
~~~
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface)
~~~
詳細的實現如下所示:
~~~
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) {
parts := strings.Split(pattern, "/")
j := 0
params := make(map[int]string)
for i, part := range parts {
if strings.HasPrefix(part, ":") {
expr := "([^/]+)"
//a user may choose to override the defult expression
// similar to expressjs: ‘/user/:id([0-9]+)’
if index := strings.Index(part, "("); index != -1 {
expr = part[index:]
part = part[:index]
}
params[j] = part
parts[i] = expr
j++
}
}
//recreate the url pattern, with parameters replaced
//by regular expressions. then compile the regex
pattern = strings.Join(parts, "/")
regex, regexErr := regexp.Compile(pattern)
if regexErr != nil {
//TODO add error handling here to avoid panic
panic(regexErr)
return
}
//now create the Route
t := reflect.Indirect(reflect.ValueOf(c)).Type()
route := &controllerInfo{}
route.regex = regex
route.params = params
route.controllerType = t
p.routers = append(p.routers, route)
}
~~~
### [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/13.2.md#靜態路由實現)靜態路由實現
上面我們實現的動態路由的實現,Go的http包默認支持靜態文件處理FileServer,由于我們實現了自定義的路由器,那么靜態文件也需要自己設定,beego的靜態文件夾路徑保存在全局變量StaticDir中,StaticDir是一個map類型,實現如下:
~~~
func (app *App) SetStaticPath(url string, path string) *App {
StaticDir[url] = path
return app
}
~~~
應用中設置靜態路徑可以使用如下方式實現:
~~~
beego.SetStaticPath("/img","/static/img")
~~~
### [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/13.2.md#轉發路由)轉發路由
轉發路由是基于ControllerRegistor里的路由信息來進行轉發的,詳細的實現如下代碼所示:
~~~
// AutoRoute
func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
if !RecoverPanic {
// go back to panic
panic(err)
} else {
Critical("Handler crashed with error", err)
for i := 1; ; i += 1 {
_, file, line, ok := runtime.Caller(i)
if !ok {
break
}
Critical(file, line)
}
}
}
}()
var started bool
for prefix, staticDir := range StaticDir {
if strings.HasPrefix(r.URL.Path, prefix) {
file := staticDir + r.URL.Path[len(prefix):]
http.ServeFile(w, r, file)
started = true
return
}
}
requestPath := r.URL.Path
//find a matching Route
for _, route := range p.routers {
//check if Route pattern matches url
if !route.regex.MatchString(requestPath) {
continue
}
//get submatches (params)
matches := route.regex.FindStringSubmatch(requestPath)
//double check that the Route matches the URL pattern.
if len(matches[0]) != len(requestPath) {
continue
}
params := make(map[string]string)
if len(route.params) > 0 {
//add url parameters to the query param map
values := r.URL.Query()
for i, match := range matches[1:] {
values.Add(route.params[i], match)
params[route.params[i]] = match
}
//reassemble query params and add to RawQuery
r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
//r.URL.RawQuery = url.Values(values).Encode()
}
//Invoke the request handler
vc := reflect.New(route.controllerType)
init := vc.MethodByName("Init")
in := make([]reflect.Value, 2)
ct := &Context{ResponseWriter: w, Request: r, Params: params}
in[0] = reflect.ValueOf(ct)
in[1] = reflect.ValueOf(route.controllerType.Name())
init.Call(in)
in = make([]reflect.Value, 0)
method := vc.MethodByName("Prepare")
method.Call(in)
if r.Method == "GET" {
method = vc.MethodByName("Get")
method.Call(in)
} else if r.Method == "POST" {
method = vc.MethodByName("Post")
method.Call(in)
} else if r.Method == "HEAD" {
method = vc.MethodByName("Head")
method.Call(in)
} else if r.Method == "DELETE" {
method = vc.MethodByName("Delete")
method.Call(in)
} else if r.Method == "PUT" {
method = vc.MethodByName("Put")
method.Call(in)
} else if r.Method == "PATCH" {
method = vc.MethodByName("Patch")
method.Call(in)
} else if r.Method == "OPTIONS" {
method = vc.MethodByName("Options")
method.Call(in)
}
if AutoRender {
method = vc.MethodByName("Render")
method.Call(in)
}
method = vc.MethodByName("Finish")
method.Call(in)
started = true
break
}
//if no matches to url, throw a not found exception
if started == false {
http.NotFound(w, r)
}
}
~~~
### [](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/13.2.md#使用入門)使用入門
基于這樣的路由設計之后就可以解決前面所說的三個限制點,使用的方式如下所示:
基本的使用注冊路由:
~~~
beego.BeeApp.RegisterController("/", &controllers.MainController{})
~~~
參數注冊:
~~~
beego.BeeApp.RegisterController("/:param", &controllers.UserController{})
~~~
正則匹配:
~~~
beego.BeeApp.RegisterController("/users/:uid([0-9]+)", &controllers.UserController{})
~~~
- 第一章 Go環境配置
- 1.1 Go安裝
- 1.2 GOPATH 與工作空間
- 1.3 Go 命令
- 1.4 Go開發工具
- 1.5 小結
- 第二章 Go語言基礎
- 2.1 你好,Go
- 2.2 Go基礎
- 2.3 流程和函數
- 2.4 struct類型
- 2.5 面向對象
- 2.6 interface
- 2.7 并發
- 2.8 總結
- 第三章 Web基礎
- 3.1 Web工作方式
- 3.2 Go搭建一個Web服務器
- 3.3 Go如何使得Web工作
- 3.4 Go的http包詳解
- 3.5 小結
- 第四章 表單
- 4.1 處理表單的輸入
- 4.2 驗證表單的輸入
- 4.3 預防跨站腳本
- 4.4 防止多次遞交表單
- 4.5 處理文件上傳
- 4.6 小結
- 第五章 訪問數據庫
- 5.1 database/sql接口
- 5.2 使用MySQL數據庫
- 5.3 使用SQLite數據庫
- 5.4 使用PostgreSQL數據庫
- 5.5 使用beedb庫進行ORM開發
- 5.6 NOSQL數據庫操作
- 5.7 小結
- 第六章 session和數據存儲
- 6.1 session和cookie
- 6.2 Go如何使用session
- 6.3 session存儲
- 6.4 預防session劫持
- 6.5 小結
- 第七章 文本處理
- 7.1 XML處理
- 7.2 JSON處理
- 7.3 正則處理
- 7.4 模板處理
- 7.5 文件操作
- 7.6 字符串處理
- 7.7 小結
- 第八章 Web服務
- 8.1 Socket編程
- 8.2 WebSocket
- 8.3 REST
- 8.4 RPC
- 8.5 小結
- 第九章 安全與加密
- 9.1 預防CSRF攻擊
- 9.2 確保輸入過濾
- 9.3 避免XSS攻擊
- 9.4 避免SQL注入
- 9.5 存儲密碼
- 9.6 加密和解密數據
- 9.7 小結
- 第十章 國際化和本地化
- 10.1 設置默認地區
- 10.2 本地化資源
- 10.3 國際化站點
- 10.4 小結
- 第十一章 錯誤處理,調試和測試
- 11.1 錯誤處理
- 11.2 使用GDB調試
- 11.3 Go怎么寫測試用例
- 11.4 小結
- 第十二章 部署與維護
- 12.1 應用日志
- 12.2 網站錯誤處理
- 12.3 應用部署
- 12.4 備份和恢復
- 12.5 小結
- 第十三章 如何設計一個Web框架
- 13.1 項目規劃
- 13.2 自定義路由器設計
- 13.3 controller設計
- 13.4 日志和配置設計
- 13.5 實現博客的增刪改
- 13.6 小結
- 第十四章 擴展Web框架
- 14.1 靜態文件支持
- 14.2 Session支持
- 14.3 表單及驗證支持
- 14.4 用戶認證
- 14.5 多語言支持
- 14.6 pprof支持
- 14.7 小結
- 附錄A 參考資料