golang web 封裝之路由

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

概述

一般的 web項目,主要兩點:路由 和 資料庫。圍繞這兩點之外就是商務邏輯。下面以幾個例子簡單談談 web項目的封裝邏輯。

封裝方式一、路由寫在 main函數中,資料庫初始串連放在 init() 函數中。地址

func init() {db.Connect()}func main() {// Configurerouter := gin.Default()// Set html render optionshtmlRender := GinHTMLRender.New()htmlRender.Debug = gin.IsDebugging()htmlRender.Layout = "layouts/default"// htmlRender.TemplatesDir = "templates/" // default// htmlRender.Ext = ".html"               // default// Tell gin to use our html renderrouter.HTMLRender = htmlRender.Create()router.RedirectTrailingSlash = truerouter.RedirectFixedPath = true// Middlewaresrouter.Use(middlewares.Connect)router.Use(middlewares.ErrorHandler)// Staticsrouter.Static("/public", "./public")// Routesrouter.GET("/", func(c *gin.Context) {c.Redirect(http.StatusMovedPermanently, "/articles")})// Articlesrouter.GET("/new", articles.New)router.GET("/articles/:_id", articles.Edit)router.GET("/articles", articles.List)router.POST("/articles", articles.Create)router.POST("/articles/:_id", articles.Update)router.POST("/delete/articles/:_id", articles.Delete)// Start listeningport := Portif len(os.Getenv("PORT")) > 0 {port = os.Getenv("PORT")}router.Run(":" + port)}

封裝方式二、路由和 db單獨封裝到一個函數中,以傳參的形式將路由傳給另一個函數。地址

func SetUpServer() {r := gin.Default()// secret 相當於簽名store, _ := sessions.NewRedisStore(10, "tcp", CONFIG.Redis.Host, CONFIG.Redis.Password, []byte(CONFIG.Server.Secret))r.Use(sessions.Sessions("session", store))r.Use(gin.Recovery())r.Use(Uniquify())r.LoadHTMLGlob("templates/*")r.Static("/static", "public/")SetUpRoutes(r)r.GET("/incr", func(c *gin.Context) {c.JSON(200, gin.H{"count": c.MustGet("key").(string)})})// var port stringr.Run(":" + CONFIG.Server.Port)}

封裝三、將路由等封裝到 Server struct 中。對此 Server 建立一個 new函數,路由等相關內容只包含在方法中。(物件導向)地址

type Server struct {Ws     *melody.MelodyRoutes *gin.EngineGames  []*Game}func New() *Server {ws := melody.New()routes := gin.Default()games := make([]*Game, 0)return &Server{Ws:     ws,Routes: routes,Games:  games,}}......func (srv *Server) RoutesInit() {srv.Routes.GET("/jq.js", func(c *gin.Context) {http.ServeFile(c.Writer, c.Request, "html/jq.js")})srv.Routes.GET("/goyaniv.js", func(c *gin.Context) {http.ServeFile(c.Writer, c.Request, "html/goyaniv.js")})srv.Routes.GET("/game/:name", func(c *gin.Context) {cookiekey, _ := c.Request.Cookie("goyanivkey")cookieid, _ := c.Request.Cookie("goyanivid")if cookieid == nil || cookiekey == nil {cookieid := CreateCookie("goyanivkey", GenerateUnique())cookiekey := CreateCookie("goyanivid", GenerateUnique())http.SetCookie(c.Writer, cookieid)http.SetCookie(c.Writer, cookiekey)}http.ServeFile(c.Writer, c.Request, "html/game.html")})srv.Routes.GET("/gamedev/:name", func(c *gin.Context) {cookiekey, _ := c.Request.Cookie("goyanivkey")cookieid, _ := c.Request.Cookie("goyanivid")if cookieid == nil || cookiekey == nil {cookieid := CreateCookie("goyanivkey", GenerateUnique())cookiekey := CreateCookie("goyanivid", GenerateUnique())http.SetCookie(c.Writer, cookieid)http.SetCookie(c.Writer, cookiekey)}http.ServeFile(c.Writer, c.Request, "html/gamedev.html")})srv.Routes.GET("/game/:name/ws", func(c *gin.Context) {srv.Ws.HandleRequest(c.Writer, c.Request)})srv.Routes.GET("/gamedev/:name/ws", func(c *gin.Context) {srv.Ws.HandleRequest(c.Writer, c.Request)})srv.Ws.HandleMessage(func(s *melody.Session, msg []byte) {FireMessage(srv, s, msg)})srv.Ws.HandleDisconnect(func(s *melody.Session) {FireDisconnect(srv, s)})srv.Ws.HandleConnect(func(s *melody.Session) {FireConnect(srv, s)})}func (s *Server) Run() {s.RoutesInit()s.Routes.Run(":5000")}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.