前言
本文主要介紹了關于golang實現路由調度的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧
項目地址
本項目依賴
使用標準庫實現,無額外依賴
為什么需要路由調度層
golang http標準庫只能精確匹配請求的URI,然后執行handler?,F在一般web項目都至少有個Controller層,以struct實現,根據不同的請求路徑派發到不同的方法中去。
路由調度器定義
由于golang暫時還不可以動態創建對象(比如java的Class.forName("xxx").newInstance(),xxx是任意存在的class名稱)。所以需要手動注冊一下controller關系。
由于golang的繼承不是一般的OOP,所以也沒有父子類這種說法,路由注冊那里只能使用interface{}
代碼實現
app/app.go
該文件為核心調度文件
package app
import ( "net/http" "reflect" "fmt")type application struct { routes map[string]interface{}}func New() *application { return &application{ routes: make(map[string]interface{}), }}func (p *application) ServeHTTP(w http.ResponseWriter, r *http.Request) { controllerName := r.URL.Query().Get("c") actionName := r.URL.Query().Get("a") if controllerName == "" || actionName == "" { http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } route, ok := p.routes[controllerName] if !ok { http.Error(w, "Controller Not Found", http.StatusNotFound) return } ele := reflect.ValueOf(route).Elem() ele.FieldByName("Request").Set(reflect.ValueOf(r)) ele.FieldByName("Response").Set(reflect.ValueOf(w)) ele.MethodByName(actionName).Call([]reflect.Value{})}func (p *application) printRoutes() { for route, controller := range p.routes { ele := reflect.ValueOf(controller).Type().String() fmt.Printf("%s %s/n", route, ele) }}func (p *application) Get(route string, controller interface{}) { p.routes[route] = controller}func (p *application) Run(addr string) error { p.printRoutes() fmt.Printf("listen on %s/n", addr) return http.ListenAndServe(addr, p)}
app/controller.go
控制器"基類"
package appimport "net/http"type Controller struct { Response http.ResponseWriter Request *http.Request}
controller/site.go
具體業務邏輯類
package controllersimport ( "fmt" "app")type SiteController struct { app.Controller}func (p SiteController) Index() { fmt.Fprint(p.Response, p.Request.RequestURI)}
main.go
入口文件
package mainimport ( _ "github.com/go-sql-driver/mysql" "app" "controllers")func main() { application := app.New() application.Get("site", &controllers.SiteController{}) application.Run(":8080")}
運行項目
啟動進程
訪問http://localhost:8080?c=site&a=Index會輸出/?c=site&a=Index
寫在最后
希望這個小小的項目能啟發到各位讀者,早日開發出適合自己的Web框架!
好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答