码迷,mamicode.com
首页 > 编程语言 > 详细

Go语言实现简单的留言本

时间:2015-03-02 22:32:04      阅读:387      评论:0      收藏:0      [点我收藏+]

标签:golang   nethttp   template   html   不转义html标签   

      做了个简单的留言本用来练习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: xcl_168@aliyun.com

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




Go语言实现简单的留言本

标签:golang   nethttp   template   html   不转义html标签   

原文地址:http://blog.csdn.net/xcl168/article/details/44024335

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!