参考原文 Writing Web Applications - Go 编程语言 略做修改后得到如下内容。
文件目录:
edit.html内容:
<h1>编辑 {{.Title}}</h1>
<form action="/save/{{.Title}}" method="POST">
<div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body}}</textarea></div>
<div><input type="submit" value="保存"></div>
</form>
view.html内容:
<h1>{{.Title}}</h1>
<p>[<a href="/edit/{{.Title}}">编辑</a>]</p>
<div>{{printf "%s" .Body}}</div>
main.go内容:
package main
import (
"fmt"
"log"
"net/http"
"io/ioutil"
"html/template"
"regexp"
)
func main() {
fmt.Printf("网站开始运行")
http.HandleFunc("/view/", makeHandler(viewHandler))
http.HandleFunc("/edit/", makeHandler(editHandler))
http.HandleFunc("/save/", makeHandler(saveHandler))
log.Fatal(http.ListenAndServe(":8080", nil))
}
func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := loadPage(title)
if err != nil {
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
return
}
renderTemplate(w, p, "view")
}
func editHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := loadPage(title)
if err != nil {
p = &Page{Title: title}
}
renderTemplate(w, p, "edit")
}
func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
body := r.FormValue("body")
p := &Page{Title: title, Body: []byte(body)}
if err := p.Save(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view/"+title, http.StatusFound)
}
var templates = template.Must(template.ParseFiles("view.html", "edit.html"))
func renderTemplate(w http.ResponseWriter, p *Page, tmpl string) {
err := templates.ExecuteTemplate(w, tmpl+".html", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
type wikiHandler = func(http.ResponseWriter, *http.Request, string)
func makeHandler(handler wikiHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
subs := validPath.FindStringSubmatch(r.URL.Path)
const cnt = 3
if len(subs) < cnt {
http.NotFound(w, r)
}
handler(w, r, subs[cnt-1])
}
}
type Page struct {
Title string // 博客标题
Body []byte // 博客内容
}
// 保存博客,这个示例是保存到本地文件
func (p *Page) Save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
// 加载博客,示例是从文件加载
func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
其他文件说明
main.exe的为go build main.go 后生成的可执行文件。
.txt的为保存的页面输入框输入的内容的数据文件。
页面可自行添加js/css等进行美化。