package main
import (
"fmt"
"log"
"net/http"
"os"
"text/template"
)
type Person struct {
Name string
age string
}
func GetTest(w http.ResponseWriter, r *http.Request){
t, err := template.ParseFiles("F:\\go_test\\src\\10_http\\index.html")
if err != nil {
fmt.Println("parse file err:", err)
return
}
p := Person{Name: "Mary", age: "31"}
file, err := os.OpenFile("testxxx.txt", os.O_CREATE|os.O_RDONLY, 0755)
defer file.Close()
if err != nil{
}
//if err := t.Execute(os.Stdout, p); err != nil { // 输出终端
//if err := t.Execute(w, p); err != nil { // 输出网页
if err := t.Execute(file, p); err != nil { // 输出文件
fmt.Println("There was an error:", err.Error())
}
}
func main() {
fmt.Println("listening...")
http.HandleFunc("/test", GetTest)
http.HandleFunc("/test1", logPanics(SimpleServer))
http.HandleFunc("/test2", logPanics(FormServer))
if err := http.ListenAndServe(":8088", nil); err != nil {
fmt.Println("listen error")
}
}
func logPanics(handle http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
defer func() {
if x := recover(); x != nil {
log.Printf("[%v] caught panic: %v", request.RemoteAddr, x)
}
}()
handle(writer, request)
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{.Name}}hello!{{.}}
</body>
</html>