Creating the Route Handler

We will create all route handlers for article related functionality in the handlers.article.go file. The handler for the index page, showIndexPage performs the following tasks:

1. Fetches the list of articles

This can be done using the getAllArticles function defined previously:

articles := getAllArticles()

2. Renders the index.html template passing it the article list

This can be done using the code below:

c.HTML(
    // Set the HTTP status to 200 (OK)
    http.StatusOK,
    // Use the index.html template
    "index.html",
    // Pass the data that the page uses
    gin.H{
        "title":   "Home Page",
        "payload": articles,
    },
)

The only difference from the version in the previous section is that we're passing the list of articles which will be accessed in the template by the variable named payload.

The handlers.article.go file should contain the following code:

// handlers.article.go

package main

import (
  "net/http"

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

func showIndexPage(c *gin.Context) {
  articles := getAllArticles()

  // Call the HTML method of the Context to render a template
  c.HTML(
    // Set the HTTP status to 200 (OK)
    http.StatusOK,
    // Use the index.html template
    "index.html",
    // Pass the data that the page uses
    gin.H{
      "title":   "Home Page",
      "payload": articles,
    },
  )

}

If you now build and run your application and visit http://localhost:8080 in a browser, it should look like this:

Article list

These are the new files added in this section:

├── common_test.go
├── handlers.article.go
├── handlers.article_test.go
├── models.article.go
├── models.article_test.go
└── routes.go

results matching ""

    No results matching ""