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 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型