This repository has been archived by the owner on Apr 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
view.go
83 lines (73 loc) · 1.82 KB
/
view.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
package main
import (
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
)
const (
PAGE_TMPL = "page.html"
)
func mainHandler(w http.ResponseWriter, r *http.Request) {
// url unescape (+ -> <Space>)
wpath := strings.Replace(r.URL.Path, "+", " ", -1)
// wpath := strings.TrimPrefix(r.URL.Path, setting.urlPrefix)
if strings.Contains(wpath, string(filepath.Separator)+".") {
log.Error("Hidden file (%s) requested",wpath)
renderError(w, wpath, http.StatusNotFound)
return
}
wf, err := loadFile(wpath)
if os.IsNotExist(err) {
log.Error(err.Error())
renderError(w, wpath, http.StatusNotFound)
return
}
if err != nil {
log.Error(err.Error())
renderError(w, err.Error(), http.StatusInternalServerError)
return
}
switch wf.fileType {
case WIKIFILE_MARKDOWN, WIKIFILE_FOLDER:
renderPage(w, wf)
case WIKIFILE_OTHER:
sendFile(w, wf)
}
}
func renderPage(w http.ResponseWriter, wf WikiFile) {
log.Info("Rendering page (%s)...", wf.WikiPath)
wp, err := loadPage(wf)
if err != nil {
log.Error(err.Error())
renderError(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.ExecuteTemplate(w, PAGE_TMPL, &wp); err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Info("OK")
}
func renderError(w http.ResponseWriter, data string, status int) {
log.Error("Rendering error view... (status: %d, data: %s)", status, data)
w.WriteHeader(status)
err := tmpl.ExecuteTemplate(w, strconv.Itoa(status)+".html", data)
if err != nil {
log.Error(err.Error())
w.Write(nil)
}
}
func sendFile(w http.ResponseWriter, wf WikiFile) {
log.Info("Sending file (%s)...", wf.WikiPath)
b, err := wf.read()
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(b)
log.Info("OK")
}