go - 将我的 HTML 链接到 Go Lang

标签 go

我正在尝试将我的结果集和变量从 .Go Lang 显示到 HTML 页面。

Assuming this tree view as my workspace. 首页.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)
    }

}

现在我如何将我的 Go 程序的值显示到 HTML 标签。 这是我的第一个 go 程序,我不太了解这种语言。我浏览了一些在线教程,但它们的编写方式并不是很有帮助。 所以对此的任何帮助将不胜感激。 谢谢

最佳答案

创建模板文件:

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>

还有你的ma​​in.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)
    }
}

在 init 函数中,您解析上面创建的模板文件。如果你有很多模板,你可以使用 ParseGlob(pattern string) (*Template, error) 但对于这个例子,你可以按名称解析模板。 完成此操作后,我们执行名为 tpl.gohtml 的模板并将其打印在 Stdout 上并处理错误。

现在您可以使用 go run main.go 运行代码,您将获得以下输出:

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

您可以看到 ExecuteTemplate() 函数的最后一个参数是您传递给模板的数据。您还可以将 slice 、映射或自行创建的复杂数据类型用于模板并对其进行迭代。

带有 slice 的 main.go

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)
    }
}

相应的模板可能是这样的

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>

这将为您提供以下输出:

<!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>

如果你想用这段代码创建 html 文件,只需使用 go run main.go > outputfilename.html

Golang Web Dev Github. Sources of a Udemy course

Go Templates

关于go - 将我的 HTML 链接到 Go Lang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50016108/

相关文章:

mysql - 使用错误的排序规则连接到 mysql 服务器?

go - 使用运算符代替函数

go - 如何取消引用动态多级指针?

go - 获取带有 ASCII 字符串字节的 base-16(十六进制)呈现的字符串

go - 使用 S3 Golang SDK 从 S3 下载选择性文件

c - 编码(marshal)处理/解封处理与序列化/反序列化之间有什么区别?

go - Go中 map 的json编码稳定吗?

json - 接口(interface)转换: interface is map[string]interface {} not

c - 将字符串文字传递给 C

time - Golang - 如何在特定时间执行功能