The handler function for the products listing page

Let's examine the products.go source file found in the handlers directory:

package handlers

import (
"net/http"

"github.com/EngineerKamesh/igb/igweb/common"
"github.com/EngineerKamesh/igb/igweb/shared/templatedata"
"github.com/isomorphicgo/isokit"
)

func ProductsHandler(env *common.Env) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
products := env.DB.GetProducts()
templateData := &templatedata.Products{PageTitle: "Products", Products: products}
env.TemplateSet.Render("products_page", &isokit.RenderParams{Writer: w, Data: templateData})
})
}

Here, we fetch the slice of products, featured on the Products page, by calling the GetProducts method on the Redis datastore object, env.DB. We declared the templateData variable of the templatedata.Products type, and it represents the data object that will be passed to the template engine, alongside the products_page template, to render the Products page. The PageTitle field represents the web page title, and the Products field is the slice of the products that are to be displayed on the Products page.

Inside the ProductsHandler function, we call the GetProducts method on the datastore object to fetch the available products for displaying from the datastore. We then create a template data instance having a PageTitle field value of "Products", and we assign the products that were fetched from the datastore to the Products field. Finally, we render the products_page template from the template set. With regard to the RenderParams object that we pass to the env.TemplateSet object's Render method, we set the Writer property to the w variable, which is http.ResponseWriter, and we set the Data property to the templateData variable, which is the data object that will be supplied to the template. At this point, the rendered web page will be sent back to the web client in the server response.

Figure 5.5 shows the rendered Products page that has been generated after accessing the /products route by visiting the following link: http://localhost:8080/products:

Figure 5.5: The Products Page

Now that we are able to display the Products page, let's take a look at the handler function for the product detail page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.41.212