dshtze500055 2018-04-25 07:09
浏览 21
已采纳

将我的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

  • 写回答

1条回答 默认 最新

  • douya7121 2018-04-27 13:53
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类