Golang Passing Complex data to HTML tutorial # 6

Golang Passing Complex data to HTML tutorial # 6

 

Golang File


package main
import (
    "html/template"
    "net/http"
)
func main() {
    type productSpecs struct {
        Size   float64
        Weight float64
        Desc   string
    }
    type product struct {
        Category string
        Name     string
        Price    float64
        Date     string
        SKU      string
        Specs    productSpecs
    }
    data := product{
        Category: "Health",
        Name:     "Tuber",
        Price:    22.22,
        Date:     "02-02-3029",
        SKU:      "32",
        Specs: productSpecs{
            Size:   22.0,
            Weight: 30.0,
            Desc:   "Here is my product desc",
        },
    }
    tmpl, _ := template.ParseGlob("templates/*.html")
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        tmpl.ExecuteTemplate(w, "index.html", data)
    })
    http.ListenAndServe(":8080", nil)
}

HTML TEMPLATE FILE


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GOLANG INDEX HTML</title>
</head>
<body>
    <h1>INDEX HTML PAGE</h1>
    Category <b>{{.Category}}</b><br/>
    Name <b>{{.Name}}</b><br/>
    Price <b>{{.Price}}</b><br/>
    Date <b>{{.Date}}</b><br/>
    SKU <b>{{.SKU}}</b><br/>
    Specs-> <br/>
    Size <b>{{.Specs.Size}}</b><br/>
    Weight <b>{{.Specs.Weight}}</b><br/>
     Desc <b>{{.Specs.Desc}}</b><br/>
</body>
</html>

Tony BB
 

TonyBB is a Coach , marketer, hypnotist and a founder of RSKVF Production who specializes in providing simple, affordable, and easy to use solutions for Life.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: