将我的HTML链接到Go Lang

I'm trying to show my result set and Variables from .Go Lang to an HTML Page.

Assuming this tree view as my workspace. Home.HTML

 <div id="Golang"><p>My Name is : <i>{{.myName}}</i></p></div>
    <div id="Golang"><p>Some Random Database Test: <br>{{.Country}} {{.City}} </p></div>

db.Go

package main

import (
    "database/sql"
    "fmt"
    "html/template"
    "log"
    "net/http"

    _ "github.com/go-sql-driver/mysql"
)

type world struct {
    Country sql.NullString `json:"country"`
    State   sql.NullString `json:"state"`
    City    sql.NullString `json:"city"`
    Abbr    string         `json:"abbriviation"`
    id      int            `json:"id"`
    CCode   int            `json:"CountryCode"`
}

func main() {

    name := "Sam"

    dsn := "root:1234@tcp(127.0.0.1:3306)/script"
    // Open database
    fmt.Println("We're going to connect a MySql Db")
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        panic(err)
    }

    defer db.Close()

    fmt.Println("Successfully connected to Mysql Db")

    results, err := db.Query("SELECT * FROM CountryDb WHERE Country =?", "India")
    if err != nil {
        panic(err.Error())
    }

    for results.Next() {
        var tag world
        err = results.Scan(&tag.Abbr, &tag.Country, &tag.CCode, &tag.State, &tag.City)
        if err != nil {
            panic(err.Error()) 
        }
        log.Printf(tag.Abbr, tag.Country, tag.CCode, tag.State, tag.City)
    }

}

Now how can i show values from my Go program to HTML Tags. This is my first go program and I'm not much aware of this language. I go through some online tutorials but the way they are written is not very helpful. so any help on this would be appreciated. Thanks

Create a template file:

tpl.gohtml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
</head>
<body>
<h1>The Number from Go Code is: {{.}}</h1> 
</body>
</html>

And your main.go

package main

import (
    "log"
    "os"
    "text/template"
)

var tpl *template.Template

func init() {
    tpl = template.Must(template.ParseFiles("tpl.gohtml"))
}

func main() {
    err := tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", 42)
    if err != nil {
        log.Fatalln(err)
    }
}

In the init function you parse the template file created above. If you have many of them you can use ParseGlob(pattern string) (*Template, error) But for this example you can parse the template by name. After we done this we execute the template with the name tpl.gohtml and print it out on the Stdout and handle errors.

Now you can run the code with go run main.go and you get the following output:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
</head>
<body>
<h1>The meaning of life: 42</h1>
</body>

You can see that the last argument of the ExecuteTemplate() Function is the data you passed to your template. You can also use slices, maps or self created complex data types to the template and iterate over it.

main.go with a slice

package main

import (
    "log"
    "os"
    "text/template"
)

var tpl *template.Template

func init() {
    tpl = template.Must(template.ParseFiles("tpl.gohtml"))
}

func main() {

    sages := []string{"This", "is", "a", "string", "slice"}

    err := tpl.Execute(os.Stdout, sages)
    if err != nil {
        log.Fatalln(err)
    }
}

and the corresponding template could look like this

tpl.gohtml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Slice Data</title>
</head>
<body>
<ul>
    {{range $index, $name := .}}
    <li>{{$index}} - {{$name}}</li>
    {{end}}
</ul>
</body>
</html>

This would give you the following output:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Slice Data</title>
</head>
<body>
<ul>

    <li>0 - This</li>

    <li>1 - is</li>

    <li>2 - a</li>

    <li>3 - string</li>

    <li>4 - slice</li>

</ul>
</body>

If you want to create the html files with this code just use go run main.go > outputfilename.html

Golang Web Dev Github. Sources of a Udemy course

Go Templates