做了个简单的留言本用来练习http与template.   


主Go代码: 

package main

//Golang版本的留言本
//author:Xiong Chuan Liang
//date:2015-3-2

import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
"log"
)

func main() {
http.Handle("/images/", http.FileServer(http.Dir("asset")))

http.HandleFunc("/", makeHandleFunc(listHandler))
http.HandleFunc("/add", makeHandleFunc(addHandler))

if err := http.ListenAndServe(":8055", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
}


type HandleFuncType func(http.ResponseWriter, *http.Request)

func makeHandleFunc(f HandleFuncType)(HandleFuncType){
return func(w http.ResponseWriter,r *http.Request){

defer func(){
if x := recover(); x!= nil {
log.Printf("[%v] panic: %v",r.RemoteAddr,x)
}
}()

f(w,r)
}
}


func addHandler(w http.ResponseWriter, r *http.Request) {
h, _ := template.ParseFiles("template/addinfo.tpl",
"template/header.tpl", "template/footer.tpl")
h.ExecuteTemplate(w, "addinfo", nil)
}

func listHandler(w http.ResponseWriter, r *http.Request) {

if r.Method == "POST" {
r.ParseForm()
if len(r.Form["note"][0]) == 0 {
infoHandler(w, r, `<b>提交失败!</b> <br/>留言不能为空! <br/> <a href="http://127.0.0.1:8055/add">返回</a>`)
return
}
info := fmt.Sprintf("留言人:<a href='mailto:%s'>%s</a><br/>留言:%s<hr>",
r.FormValue("email"), //r.Form.Get("email")
r.FormValue("nickname"),
r.FormValue("note"))
writeInfo(info)
}

list, _ := readInfo()
msg := map[string]template.HTML{"List": template.HTML(list)}

h, _ := template.ParseFiles("template/guestbook.tpl",
"template/header.tpl", "template/footer.tpl")
h.ExecuteTemplate(w, "guestbook", msg)
}

func infoHandler(w http.ResponseWriter, r *http.Request, info string) {
var base = `
<!DOCTYPE html>
<html>
<head>
<title>info</title>
<meta charset="UTF-8">
</head>
<body>
{{.}}
</body>
</html>
`
tmpl, err := template.New("提示信息").Parse(base)
if err != nil {
panic(err)
}

err = tmpl.Execute(w, template.HTML(info))
if err != nil {
panic(err)
}
}

const FILENAME = "Guestbook.log"

func readInfo() (string, error) {
body, err := ioutil.ReadFile(FILENAME)
if err != nil {
return "", err
}
return string(body), nil
}

func writeInfo(str string) bool {
f, err := os.OpenFile(FILENAME, os.O_RDWR|os.O_APPEND|os.O_CREATE, os.ModeType)
if err != nil {
panic(err)
}
defer f.Close()
_, err = f.WriteString(str)
if err != nil {
panic(err)
}
return true
}




其guestbook.tpl:

{{define "guestbook"}}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>留言本</title>
<style type="text/css">
body{
margin:0;
padding:0;
background:#EAEAEA;
}
</style>
</head>
<body>

{{template "header"}}

{{.List}}

<center><a href="http://127.0.0.1:8055/add">增加留言</a></center>

{{template "footer"}}

</body>
</html>
{{end}}


实现的效果如下:

Go语言实现简单的留言本_golang


Go语言实现简单的留言本_nethttp_02


整个源码打包在此: ​​ 点击下载​​