aboutsummaryrefslogtreecommitdiff
path: root/handler.go
diff options
context:
space:
mode:
Diffstat (limited to 'handler.go')
-rw-r--r--handler.go67
1 files changed, 67 insertions, 0 deletions
diff --git a/handler.go b/handler.go
new file mode 100644
index 0000000..04d6d94
--- /dev/null
+++ b/handler.go
@@ -0,0 +1,67 @@
+package main
+
+import (
+ "io/ioutil"
+ "net/http"
+ "text/template"
+)
+
+func init() {
+ http.HandleFunc("/index", indexHandler)
+ http.HandleFunc("/view/", viewHandler)
+ http.HandleFunc("/edit/", editHandler)
+ http.HandleFunc("/del/", delHandler)
+ 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 homeHandler(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, "/view/Home", http.StatusFound)
+}