我正在使用 html/template 来提供 html,但我不确定我是否正确使用它。我只粘贴了下面的相关代码(不完整):
这是我的 Go 代码:
func homehandler(w http.ResponseWriter, r *http.Request) {
userName := getUserName(r) //this is defined somewhere
if userName != "" {
t := template.Must(template.New("Tele").Parse(homePage))
t.Execute(w, ReadData()) //ReadData() is a function that reads from the MySQL database and returns a string array
} else {
(...some code)
}
}
func ReadData() ([]string) {
db, _ := sql.Open("mysql", "user1@/my_db")
(...some code)
rows, err := db.Query("select tweet from posts where username = ?", AddUser.Name) //AddUser is defined somewhere
(...some code)
for rows.Next() {
err := rows.Scan(&tweet)
if err != nil {
fmt.Println(err)
}
v := append(tweetarray, tweet)
fmt.Println(v)
return v
}
return []string{}
}
Go 代码中的 html 部分:
const homePage = `
<html>
<h1>hi {{ .userName}}</h1>
<form action="/home/tweets" method="POST">
<label for="name">Tweet</label>
<input type="text" id="tweet" name="twt"</input>
<button type="Tweet">Tweet</button>
<h2>{{range $i := .tweetarray}} {{ $i }} {{end}}</h2>
`
HTML 根本不出现。我在代码中做错了什么?
浮云间
相关分类