aboutsummaryrefslogtreecommitdiff
path: root/handler.go
blob: 369da4059492afed0e63252080502b22f4ff16d9 (plain)
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
package main

import (
	"io/ioutil"
	"net/http"
	"text/template"
)

func init() {
	http.Handle("/css/", http.FileServer(http.Dir("assets")))
	http.Handle("/fonts/", http.FileServer(http.Dir("assets")))
	http.HandleFunc("/index", indexHandler)
	http.HandleFunc("/view/", viewHandler)
	http.HandleFunc("/edit/", editHandler)
	http.HandleFunc("/del/", delHandler)
	http.HandleFunc("/save/", saveHandler)
	http.HandleFunc("/", homeHandler)
}

var (
	indextmpl = template.Must(template.ParseFiles("tmpl/root", "tmpl/index"))
	viewtmpl  = template.Must(template.ParseFiles("tmpl/root", "tmpl/view"))
	edittmpl  = template.Must(template.ParseFiles("tmpl/root", "tmpl/edit"))
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
	files, err := ioutil.ReadDir("data")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	p := new(Page)
	for _, entry := range files {
		file := entry.Name()
		if !entry.IsDir() && file[0] != '.' {
			p.Pages = append(p.Pages, entry)
		}
	}
	p.render(w, indextmpl)
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/view/"):]
	p, err := loadPage(title)
	if err != nil {
		http.Redirect(w, r, "/edit/"+title, http.StatusFound)
		return
	}
	p.render(w, viewtmpl)
}

func editHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/edit/"):]
	p, _ := loadPage(title)
	p.render(w, edittmpl)
}

func delHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/del/"):]
	p := &Page{Title: title}
	if err := p.del(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/", http.StatusFound)
}

func saveHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/save/"):]
	p := &Page{Title: title, Body: []byte(r.FormValue("body"))}
	if err := p.save(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/view/Home", http.StatusFound)
}