Source file doc/articles/wiki/final.go
1
2
3
4
5 package main
6
7 import (
8 "html/template"
9 "io/ioutil"
10 "net/http"
11 "regexp"
12 )
13
14 type Page struct {
15 Title string
16 Body []byte
17 }
18
19 func (p *Page) save() error {
20 filename := p.Title + ".txt"
21 return ioutil.WriteFile(filename, p.Body, 0600)
22 }
23
24 func loadPage(title string) (*Page, error) {
25 filename := title + ".txt"
26 body, err := ioutil.ReadFile(filename)
27 if err != nil {
28 return nil, err
29 }
30 return &Page{Title: title, Body: body}, nil
31 }
32
33 func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
34 p, err := loadPage(title)
35 if err != nil {
36 http.Redirect(w, r, "/edit/"+title, http.StatusFound)
37 return
38 }
39 renderTemplate(w, "view", p)
40 }
41
42 func editHandler(w http.ResponseWriter, r *http.Request, title string) {
43 p, err := loadPage(title)
44 if err != nil {
45 p = &Page{Title: title}
46 }
47 renderTemplate(w, "edit", p)
48 }
49
50 func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
51 body := r.FormValue("body")
52 p := &Page{Title: title, Body: []byte(body)}
53 err := p.save()
54 if err != nil {
55 http.Error(w, err.Error(), http.StatusInternalServerError)
56 return
57 }
58 http.Redirect(w, r, "/view/"+title, http.StatusFound)
59 }
60
61 var templates = template.Must(template.ParseFiles("edit.html", "view.html"))
62
63 func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
64 err := templates.ExecuteTemplate(w, tmpl+".html", p)
65 if err != nil {
66 http.Error(w, err.Error(), http.StatusInternalServerError)
67 }
68 }
69
70 const lenPath = len("/view/")
71
72 var titleValidator = regexp.MustCompile("^[a-zA-Z0-9]+$")
73
74 func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
75 return func(w http.ResponseWriter, r *http.Request) {
76 title := r.URL.Path[lenPath:]
77 if !titleValidator.MatchString(title) {
78 http.NotFound(w, r)
79 return
80 }
81 fn(w, r, title)
82 }
83 }
84
85 func main() {
86 http.HandleFunc("/view/", makeHandler(viewHandler))
87 http.HandleFunc("/edit/", makeHandler(editHandler))
88 http.HandleFunc("/save/", makeHandler(saveHandler))
89 http.ListenAndServe(":8080", nil)
90 }
View as plain text