Go基礎學習記錄 - 編寫Web應用程式 - 路由和程式啟動的一些思考
近段時間重新對我的Web應用程式進行了一些思考,首先程式啟動的main.go檔案中,暫時的路由新增沒有太大的問題,但是根據以往的專案開發經驗,如果這個系統對外分享的話,之後在做大專案的時候,會遇到新增很多路由的情況,然後就會發現檔案變的越來越大,關鍵是路由還放在了main.go檔案中,這個實在是太麻煩了,於是今天做了下少許的改動。
每次我都會將自己實踐的程式碼放到github上並且都會打一個tag,方便後面用的同學使用,這裡我以下面分支的程式碼進行實踐分享
https://github.com/durban89/typescript_demo.git tag: 1.0.12
1、改動main.go檔案
將原來的
http.HandleFunc("/view/", helpers.MakeHandler(controllers.ArticleView)) http.HandleFunc("/save/", helpers.MakeHandler(controllers.ArticleSave)) http.HandleFunc("/edit/", helpers.MakeHandler(controllers.ArticleEdit)) http.HandleFunc("/upload/", controllers.UploadHandler) http.HandleFunc("/postFile/", controllers.PostFileHandler)
用下面的程式碼替換掉
router.Routes()
這樣我們將路由這一塊的邏輯分到一個負責路由的檔案來做處理,這樣main.go檔案就看起來很簡潔。
2、新增router.go
建立檔案router/router.go,新增程式碼如下
package router import ( "net/http" "github.com/durban89/wiki/controllers" ) // RouterMap 路由 type RouterMap struct { Path string Fnfunc(http.ResponseWriter, *http.Request) } // RouterMaps 路由列表 var RouterMaps = []*RouterMap{ { Path: "/view/", Fn:controllers.ArticleViewWithID, }, { Path: "/save/", Fn:controllers.ArticleViewWithID, }, { Path: "/edit/", Fn:controllers.ArticleViewWithID, }, { Path: "/upload/", Fn:controllers.UploadHandler, }, { Path: "/postFile/", Fn:controllers.PostFileHandler, }, } // Routes 操作 func Routes() { for i := 0; i < len(RouterMaps); i++ { cRoute := RouterMaps[i] http.HandleFunc(cRoute.Path, cRoute.Fn) } }
從上面的程式碼可以看出來,路由的管理稍微好一些了,這也就達到了我們優化main.go檔案的目的。
3、測試
在controllers/article.go檔案中新增如下函式
func ArticleViewWithID(w http.ResponseWriter, r *http.Request) { if strings.ToLower(r.Method) == "get" { var validPath = regexp.MustCompile("^/(view)/([a-zA-Z0-9]+)$") m := validPath.FindStringSubmatch(r.URL.Path) if m == nil { http.NotFound(w, r) return } // 獲取文章標題或者文章ID fmt.Println(m[2:]) fmt.Fprintf(w, "Welcome to the home page!") return } http.NotFound(w, r) return }
新增完之後,重新編譯專案並執行,一切正常。
專案更新地址
https://github.com/durban89/typescript_demo.git tag: 1.1.0