Code
package main
import(
"fmt"
"net/http"
"html/template"
)
var myTemplate *template.template
type Person struct{
Name string
Age string
Title string
}
func userInfo(w http.ResponseWriter, r *http.Request){
fmt.Println("handle hello")
p := Person{
Name: "Alex",
Age: "19",
Title: "天津科技大学",
}
myTemplate.Execute(w, p)
}
func initTemplate(filename string) (err error){
myTemplate, err := template.ParseFiles(filename)
if err != nil{
fmt.Println("prase file err: ", err)
return
}
return } func main(){
initTemplate("./index.html")
http.HandleFunc("/user/info", userInfo)
err := http.ListenAndServer("0.0.0.0:5050", nil)
if err != nil{
fmt.Println("http listen failed")
}
}
报错:./main.go:9:17: cannot refer to unexported name template.template
拼写错误,改为
var myTemplate *template.Template
报错:./main.go:39:12: undefined: http.ListenAndServer
拼写错误,改为
err := http.ListenAndServe("0.0.0.0:5050", nil)
报错:./main.go:28:5: myTemplate declared and not used
myTemplate, err = template.ParseFiles(filename)