1 回答
TA贡献1831条经验 获得超4个赞
所以我已经修复了你的代码,但对它持怀疑态度,因为我没有测试它。请记住,原始代码中的一些事情是完全错误的。仅举一例,处理程序从全局变量中获取响应。这是灾难的秘诀,你需要“不习惯”才能做到这一点,否则它会给你带来麻烦。
我能说的最好的是让你的老师审查这个代码。
main.go
package main
import (
"database/sql"
"net/http"
"text/template"
_ "github.com/go-sql-driver/mysql"
)
type product struct {
ID int
Name string
Stock int
Price float32
}
func handler(w http.ResponseWriter, r *http.Request) {
appointment, _ := template.ParseFiles("ot.html")
appointment.Execute(w, GetProducts())
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func GetProducts() []product {
var out = make([]product, 0, 10)
sqlType := "mysql"
sqlUsn := "root"
sqlPass := "2582064"
sqlDatabase := "gowdb"
db, err := sql.Open(sqlType, sqlUsn+":"+sqlPass+"@/"+sqlDatabase)
if err != nil {
panic(err.Error())
}
defer db.Close()
results, err := db.Query("SELECT * FROM products")
if err != nil {
panic(err.Error())
}
for results.Next() {
var p product
err = results.Scan(&p.ID, &p.Stock, &p.Price, &p.Name)
if err != nil {
panic(err.Error())
}
out = append(out, p)
}
if err != nil {
panic(err.Error())
}
return out
}
断续器
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{{ range $i, $e := . }}
<h1>PRODUCT $i</h1>
<div>NAME: {{.Name}}</div>
<div>PRICE: {{.Price}}</div>
<div>STOCK: {{.Stock}}</div>
<div>ID: {{.ID}}</div>
<div>BUY FROM: xxx.com</div>
{{end}}
</body>
</html>
- 1 回答
- 0 关注
- 127 浏览
添加回答
举报