aboutsummaryrefslogtreecommitdiff
path: root/http.go
blob: c6aec32863ce792a5d3848999192109255cc77f8 (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
81
82
83
84
85
86
package main

import (
	"html/template"
	"net/http"
)

type Index struct {
	Wiki
	*template.Template
}

func (i Index) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	pages, err := i.Wiki.List()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	p := Page{Pages: pages}
	if err := p.Render(w, i.Template); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

type View struct {
	Wiki
	*template.Template
}

func (v View) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	title := r.PathValue("title")
	p, err := v.Wiki.Load(title)
	if err != nil {
		http.Redirect(w, r, "/edit/"+title, http.StatusFound)
		return
	}
	if err := p.Render(w, v.Template); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

type Edit struct {
	Wiki
	*template.Template
}

func (e Edit) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	title := r.PathValue("title")
	p, _ := e.Wiki.Load(title)
	if err := p.Render(w, e.Template); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

type Delete struct {
	Wiki
}

func (d Delete) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	title := r.PathValue("title")
	if err := d.Delete(title); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/", http.StatusFound)
}

type Save struct {
	Wiki
}

func (s Save) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	title := r.PathValue("title")
	p := Page{
		Title: title,
		Body:  []byte(r.FormValue("body")),
	}
	if err := s.Save(p); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}