-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
51 lines (40 loc) · 1.16 KB
/
handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"book/models"
"net/http"
"regexp"
)
var valURL = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
func makeHandler(fn func(w http.ResponseWriter, r *http.Request, t string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := valURL.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return
}
fn(w, r, m[2])
}
}
func loadHandler(res http.ResponseWriter, req *http.Request, title string) {
p, e := models.LoadPage(title + ".txt")
if e != nil {
http.Redirect(res, req, "/edit/"+title, http.StatusFound)
return
}
renderTemplate("view", res, p)
}
func editHandler(res http.ResponseWriter, req *http.Request, title string) {
p, e := models.LoadPage(title + ".txt")
if e != nil {
p = &models.Page{Title: title, Body: []byte("")}
}
renderTemplate("edit", res, p)
}
func saveHandler(res http.ResponseWriter, req *http.Request, title string) {
p := &models.Page{Title: title, Body: []byte(req.FormValue("changed"))}
e := p.SavePage()
if e != nil {
http.Error(res, e.Error(), http.StatusInternalServerError)
}
http.Redirect(res, req, "/view/"+p.Title, http.StatusFound)
}