golang web基础应用
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
}
}