main.go
package main
import(
"fmt"
"html/template"
"net/http"
)
// main.go
type UserInfo struct {
Name string
Gender string
Age int
}
func sayHello(w http.ResponseWriter, request *http.Request) {
// 解析指定文件生成模板对象
tmpl, err := template.ParseFiles("./template/hello.tmpl","./template/menu.tmpl")
if err != nil {
fmt.Println("create template failed, err:", err)
return
}
//Get from URL
url := request.URL
values := url.Query()
userName := values.Get("userName")
password := values.Get("password")
println(userName, password)
//go template
user:= UserInfo{//首字一定要大写,即公共变量public,否则是私有变量private
Name: "小王子",
Gender: "男",
Age: 18,
}
//method 2:
m1:=map[string] interface{}{
"name": "小王子2",
"gender": "男2",
"age": 182,
}
hobbyList:=[]string{
"唱",
"死",
"爱",
}
//write user or m1 to template
//tmpl.Execute(w, m1)
//method 2 write a map with user and m1
tmpl.Execute(w, map[string] interface{}{
"user":user,
"m1":m1,
"hobby":hobbyList,
})
}
func selfFunc(w http.ResponseWriter, request *http.Request) {
kua := func(name string) (string, error) {
return name + "真帅", nil
}
t:=template.New("t.tmpl")
t.Funcs(template.FuncMap{
"kua":kua,
})
_, err := t.ParseFiles("./template/t.tmpl")
if err != nil {
fmt.Println("create template failed, err:", err)
return
}
name:="youareadog"
// output with {{ kua .}}
t.Execute(w, name)
}
func main() {
http.HandleFunc("/hello", sayHello)
http.HandleFunc("/selfFunc", selfFunc)
err := http.ListenAndServe(":9092", nil)
if err != nil {
fmt.Println("HTTP server failed,err:", err)
return
}
}
hello.tmpl
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello</title>
</head>
<body>
<h4>脑没装</h4>
{{/*注释*/}}
<p>Hello {{.user.Name}}</p>
<p>性别:{{.user.Gender}}</p>
<p>年龄:{{.user.Age}}</p>
<p>Hello2 {{.m1.name}}</p>
<p>性别2:{{.m1.gender}}</p>
<p>年龄2:{{.m1.age}}</p>
<!--
<p>Hello {{.Name}}</p>
<p>性别:{{.Gender}}</p>
<p>年龄:{{.Age}}</p>
-->
<hr />
{{range $index,$hobby := .hobby }}
<p>{{$index}} - {{$hobby}}</p>
{{end}}
<hr />
{{with .m1}}
<p>{{.name}}</p>
{{end}}
<hr />
<p>{{index .hobby 2}}</p>
<hr />
{{template "menu.tmpl"}}
//模板嵌套,在main.go中按顺利加入即要
</body>
</html>