Go語言實現簡單的留言本

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

      做了個簡單的留言本用來練習http與template.   


主Go代碼: 

package main//Golang版本的留言本//author:Xiong Chuan Liang//date:2015-3-2import ("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}}

實現的效果如下:





整個源碼打包在此: 點擊下載


MAIL: xcl_168@aliyun.com

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




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.