duaabhuv188411 2018-06-08 21:21
浏览 88
已采纳

在Golang网站中使用模板显示mysql表

I am in the process learning GoLang web development, where I am trying a simple example of display a table in mysql database at Webpage rendered using Golang template. Below is the snippet of my code, which is not working.Table rendering is failing,where range function at template not working

Server.go

package main

import (
    "fmt"
    "net/http"
    _ "github.com/go-sql-driver/mysql"
    "database/sql"
    "os"
    "html/template"
)

type Employee struct {
    fname, sname, dname, email string
}

func helloWorld(w http.ResponseWriter, r *http.Request){
    name, err := os.Hostname()
    checkErr(err)
    fmt.Fprintf(w, "HOSTNAME : %s
", name)
}

func dbConnect() (db *sql.DB) {
    dbDriver := "mysql"
    dbUser := "root"
    dbPass := "password"
    dbHost := "mysql.go"
    dbPort := "3306"
    dbName := "company"
    db, err := sql.Open(dbDriver, dbUser +":"+ dbPass +"@tcp("+ dbHost +":"+ dbPort +")/"+ dbName +"?charset=utf8")
    checkErr(err)
    return db
}

func dbSelect() []Employee{
    db := dbConnect()
    rows, err := db.Query("select * from employees")
    checkErr(err)

    employee := Employee{}
    employees := []Employee{}

    for rows.Next() {
        var first_name, last_name, department, email string
        err = rows.Scan(&first_name, &last_name, &department, &email)
        checkErr(err)
        employee.fname = first_name
        employee.sname = last_name
        employee.dname = department
        employee.email = email
        employees = append(employees, employee)

    }
    defer db.Close()
    return employees
}

var tmpl = template.Must(template.ParseFiles("layout.html"))
//var tmpl = template.Must(template.ParseGlob("layout.html"))
func dbTableHtml(w http.ResponseWriter, r *http.Request){
    table := dbSelect()
    tmpl.ExecuteTemplate(w, "Index", table)
}

func dbTable(w http.ResponseWriter, r *http.Request){
    table := dbSelect()
    for i := range(table) {
        emp := table[i]
        fmt.Fprintf(w,"YESS|%12s|%12s|%12s|%20s|
" ,emp.fname ,emp.sname ,emp.dname ,emp.email)
    }
}

func main() {
    http.HandleFunc("/", helloWorld)
    http.HandleFunc("/view", dbTableHtml) 
    http.HandleFunc("/raw", dbTable)
    http.ListenAndServe(":8080", nil)
}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

layout.html

{{ define "Index" }}
<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>Maithanam Website</title>
        <meta charset="UTF-8" />
    </head>
    <body>
        <h1>Maithanammm website for mysql</h1> 

    {{ $length := len . }}
    <h3>Length {{$length}}</h3> 

    <table border="1">
      <tr>
        <td>FirstName</td>
        <td>SecondName</td>
        <td>Department</td>
        <td>Email</td>
      </tr>
    {{ range . }}
      <tr>
        <td>{{ .fname }}</td>
        <td> {{ .sname }} </td>
        <td>{{ .dname }} </td>
        <td>{{ .email }} </td>
      </tr>
    {{ end }}
    </table>

    </body>
</html>
{{ end }}

WebPage enter image description here

  • 写回答

1条回答 默认 最新

  • douren1928 2018-06-08 22:15
    关注

    You have two problems:

    1. You're not checking for errors when you call ExecuteTemplate.
    2. Your template is using non-exported fields, taking care of your first problem would have told you this.

    For the first problem:

    err := tmpl.ExecuteTemplate(w, "Index", table)
    if err != nil {
        // Do something with the error
    }
    

    For the second problem, change your struct to have exported fields:

    type Employee struct {
        Fname, Sname, Dname, Email string
    }
    

    and then change your template to use the new field names.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器