gpt4 book ai didi

GO:使用 html/template 提供模板时出错

转载 作者:IT王子 更新时间:2023-10-29 02:34:29 27 4
gpt4 key购买 nike

我正在使用 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 根本没有出现。我在代码中做错了什么?

最佳答案

检查你的错误!(很抱歉粗体,但这是很多 Go 问题的答案)

t.Execute() 返回错误,因为您的模板中的 html 格式不正确。

html/template:Tele: "<" in attribute name: "</input>\n<button type=\"Tweet\">Tw"

在对此类问题进行故障排除时,请尝试单独运行每个部分,或者至少记录一些调试信息。

关于GO:使用 html/template 提供模板时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25309092/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com