我有一个Golang模板,将我的html解释为纯文本。
我在传递给w.Header().Set("Content-Type", "text/html; charset=utf-8")的函数中加入了行http.HandleFunc(),但是我的html被解释为纯文本。
package main
import (
"html/template"
"io"
"net/http"
)
func main() {
http.HandleFunc("/dog", dog)
http.Handle("/resources/", http.StripPrefix("/resources", http.FileServer(http.Dir("./assets"))))
http.ListenAndServe(":8080", nil)
}
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseFiles("index.gohtml"))
}
func dog(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := []string{`
This is from dog
`, ` `}tpl.ExecuteTemplate(w, "index.gohtml", data)
}
这是我的index.gohtml模板:
Document{{range .}}
{{.}}
{{end}}