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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?