Setting Up the Route

In the previous section, we created the route and the route definition in the main.go file itself. As the application grows, it would make sense to move the routes definitions in its own file. We'll create a function initializeRoutes() in the routes.go file and call this function from the main() function to set up all the routes. Instead of defining the route handler inline, we'll define them as separate functions.

After making these changes, the routes.go file will contain the following:

// routes.go

package main

func initializeRoutes() {

  // Handle the index route
  router.GET("/", showIndexPage)
}

Since we'll be displaying the list of articles on the index page, we don't need to define any additional routes after we've refactored the code.

The main.go file should contain the following code:

// main.go

package main

import "github.com/gin-gonic/gin"

var router *gin.Engine

func main() {

  // Set the router as the default one provided by Gin
  router = gin.Default()

  // Process the templates at the start so that they don't have to be loaded
  // from the disk again. This makes serving HTML pages very fast.
  router.LoadHTMLGlob("templates/*")

  // Initialize the routes
  initializeRoutes()

  // Start serving the application
  router.Run()

}

results matching ""

    No results matching ""