-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathadd_append.go
63 lines (59 loc) · 1.52 KB
/
add_append.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
52
53
54
55
56
57
58
59
60
61
62
63
package main
import (
"bytes"
"log"
"net/http"
)
// addHandler uses the "add.html" template to present an empty edit
// page. What you type there is appended to the page using the
// appendHandler.
func addHandler(w http.ResponseWriter, r *http.Request, name string) {
p, err := loadPage(name)
if err != nil {
p = &Page{Title: name, Name: name}
} else {
p.handleTitle(false)
}
renderTemplate(w, p.Dir(), "add", p)
}
// appendHandler takes the "body" form parameter and appends it. The browser is redirected to the page view. This is
// similar to the saveHandler.
func appendHandler(w http.ResponseWriter, r *http.Request, name string) {
body := r.FormValue("body")
p, err := loadPage(name)
if err != nil {
p = &Page{Name: name, Body: []byte(body)}
} else {
p.append([]byte(body))
}
p.handleTitle(false)
err = p.save()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
username, _, ok := r.BasicAuth()
if ok {
log.Println("Save", name, "by", username)
} else {
log.Println("Save", name)
}
if r.FormValue("notify") == "on" {
err = p.notify()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
http.Redirect(w, r, "/view/"+name, http.StatusFound)
}
func (p *Page) append(body []byte) {
// ensure an empty line at the end
if bytes.HasSuffix(p.Body, []byte("\n\n")) {
} else if bytes.HasSuffix(p.Body, []byte("\n")) {
p.Body = append(p.Body, '\n')
} else {
p.Body = append(p.Body, '\n', '\n')
}
p.Body = append(p.Body, body...)
}