forked from emad-elsaid/xlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
116 lines (94 loc) · 2.47 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package xlog
import (
"context"
"flag"
"log"
"os"
"runtime"
)
// Define the catch all HTTP routes, parse CLI flags and take actions like
// building the static pages and exit, or start the HTTP server
func Start(ctx context.Context) {
runtime.GOMAXPROCS(runtime.NumCPU() * 2)
flag.Parse()
// Program Core routes. View, Edit routes and a route to write new content
// to the page. + handling root path which just show `index` page.
Get("/{$}", rootHandler)
Get("/+/edit/{page...}", getPageEditHandler)
Get("/{page...}", getPageHandler)
Post("/{page...}", postPageHandler)
if err := os.Chdir(SOURCE); err != nil {
log.Fatal(err)
}
if len(BUILD) > 0 {
READONLY = true
if err := buildStaticSite(BUILD); err != nil {
log.Printf("%s", err.Error())
}
os.Exit(0)
}
srv := server()
log.Printf("Starting server: %s", bindAddress)
go func() {
select {
case <-ctx.Done():
srv.Close()
return
}
}()
srv.ListenAndServe()
}
// Redirect to `/index` to render the index page.
func rootHandler(w Response, r Request) Output {
return Redirect("/" + INDEX)
}
// Shows a page. the page name is the path itself. if the page doesn't exist it
// redirect to edit page otherwise will render it to HTML
func getPageHandler(w Response, r Request) Output {
page := NewPage(r.PathValue("page"))
if !page.Exists() {
if output, err := staticHandler(r); err == nil {
return output
}
if READONLY {
return NotFound("can't find page")
}
return Redirect("/+/edit/" + page.Name())
}
return Render("view", Locals{
"title": page.Emoji() + " " + page.Name(),
"page": page,
"edit": "/+/edit/" + page.Name(),
"content": page.Render(),
"csrf": CSRF(r),
})
}
// Edit page, gets the page from path
func getPageEditHandler(w Response, r Request) Output {
if READONLY {
return Unauthorized("Readonly mode is active")
}
page := NewPage(r.PathValue("page"))
var content Markdown
if page.Exists() {
content = page.Content()
}
return Render("edit", Locals{
"title": page.Emoji() + " " + page.Name(),
"page": page,
"commands": Commands(page),
"content": content,
"autocomplete": autocompletes,
"csrf": CSRF(r),
})
}
// Save new content of the page
func postPageHandler(w Response, r Request) Output {
if READONLY {
return Unauthorized("Readonly mode is active")
}
page := NewPage(r.PathValue("page"))
content := r.FormValue("content")
page.Write(Markdown(content))
return Redirect("/" + page.Name())
}