前言
本文主要介紹了關(guān)于golang實(shí)現(xiàn)路由調(diào)度的相關(guān)內(nèi)容,分享出來(lái)供大家參考學(xué)習(xí),下面話不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧
項(xiàng)目地址
本項(xiàng)目依賴(lài)
使用標(biāo)準(zhǔn)庫(kù)實(shí)現(xiàn),無(wú)額外依賴(lài)
為什么需要路由調(diào)度層
golang http標(biāo)準(zhǔn)庫(kù)只能精確匹配請(qǐng)求的URI,然后執(zhí)行handler。現(xiàn)在一般web項(xiàng)目都至少有個(gè)Controller層,以struct實(shí)現(xiàn),根據(jù)不同的請(qǐng)求路徑派發(fā)到不同的方法中去。
路由調(diào)度器定義
由于golang暫時(shí)還不可以動(dòng)態(tài)創(chuàng)建對(duì)象(比如java的Class.forName("xxx").newInstance(),xxx是任意存在的class名稱(chēng))。所以需要手動(dòng)注冊(cè)一下controller關(guān)系。
由于golang的繼承不是一般的OOP,所以也沒(méi)有父子類(lèi)這種說(shuō)法,路由注冊(cè)那里只能使用interface{}
代碼實(shí)現(xiàn)
app/app.go
該文件為核心調(diào)度文件
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
控制器"基類(lèi)"
package appimport "net/http"type Controller struct { Response http.ResponseWriter Request *http.Request}
controller/site.go
具體業(yè)務(wù)邏輯類(lèi)
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")}
運(yùn)行項(xiàng)目
啟動(dòng)進(jìn)程
訪問(wèn)http://localhost:8080?c=site&a=Index會(huì)輸出/?c=site&a=Index
寫(xiě)在最后
希望這個(gè)小小的項(xiàng)目能啟發(fā)到各位讀者,早日開(kāi)發(fā)出適合自己的Web框架!
好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)VEVB武林網(wǎng)的支持。
|
新聞熱點(diǎn)
疑難解答
圖片精選