-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
81 lines (69 loc) · 1.96 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"log"
"net/http"
"time"
)
func verifyCookie(r *http.Request) bool {
token, err := getCookie(r,"token")
if err != nil {
log.Println("[ERROR]: ", err)
return false
}
return verifyToken(token)
}
func homePageHandler(w http.ResponseWriter, r *http.Request) {
if !verifyCookie(r) {
http.Redirect(w, r, "/login/", http.StatusFound)
return
}
renderTemplates(w, "home", nil)
}
func ViewAllHandler(w http.ResponseWriter, r *http.Request) {
renderTemplates(w, "views", data)
}
func renderTemplates(w http.ResponseWriter, tmpl string, page []Page) {
err := templates.ExecuteTemplate(w, tmpl+".html", page)
if err != nil {
log.Printf("[Error] in viewing all pages: %s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func ViewHandler(w http.ResponseWriter, r *http.Request, title string) {
page, err := loadPage(title)
if err != nil {
log.Printf("[Warning]: %s", err)
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
return
}
renderTemplate(w, "view", page)
}
func SaveHandler(w http.ResponseWriter, r *http.Request, title string) {
body := r.FormValue("body")
println("body", body)
author := r.FormValue("author")
page := &Page{Title: title, Body: []byte(body), Author: author, CreatedAt: time.Now(), ModifiedAt: time.Now()}
if len(body) != 0 {
page.save()
}
// renderTemplate(w, "edit", page) // don't have multiple responses
http.Redirect(w, r, "/view/"+title, http.StatusFound)
}
func EditHandler(w http.ResponseWriter, r *http.Request, title string) {
page, err := loadPage(title)
if err != nil {
page = &Page{Title: title, CreatedAt: time.Now(), ModifiedAt: time.Now()}
}
renderTemplate(w, "edit", page)
}
func MyHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := validPath.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return
}
fn(w, r, m[2])
}
}