Go语言实现简单的留言本

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


主Go代码: 

package main

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

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

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

	http.HandleFunc("/", listHandler)
	http.HandleFunc("/add", addHandler)
	http.ListenAndServe(":8055", nil)
}

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.Form.Get("email"),
			r.Form.Get("nickname"),
			r.Form.Get("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}}

实现的效果如下:

技术分享


技术分享


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


MAIL: [email protected]

BLOG: http://blog.csdn.net/xcl168




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。