-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (64 loc) · 1.61 KB
/
main.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func home(w http.ResponseWriter, req *http.Request) {
fmt.Fprint(w, newTemplate())
}
func stat(w http.ResponseWriter, req *http.Request) {
p := cleanSlash(req.FormValue("path"))
info, err := os.Stat(store.workingPath + p)
var resp *File
if err != nil {
resp = &File{
Name: markdownName(p),
Path: p,
}
} else {
resp = &File{
Name: markdownName(p),
Path: p,
Size: info.Size(),
Exists: true,
UpdatedAt: info.ModTime().UnixNano(),
}
}
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Fprint(w, jsonEncode(resp))
}
func file(w http.ResponseWriter, req *http.Request) {
html, err := markdown(store.workingPath + cleanSlash(req.FormValue("path")))
if err != nil {
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Fprint(w, html)
}
func files(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Fprint(w, jsonEncode(getFiles(store.workingPath)))
}
func forward(w http.ResponseWriter, req *http.Request) {
p := store.workingPath + cleanSlash(req.URL.Query().Get("path"))
if _, err := os.Stat(p); err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
if data, err := ioutil.ReadFile(p); err == nil {
w.Header().Set("Content-Type", contentType(p))
w.Write(data)
return
}
w.WriteHeader(http.StatusInternalServerError)
}
func main() {
http.HandleFunc("/", home)
http.HandleFunc("/stat", stat)
http.HandleFunc("/file", file)
http.HandleFunc("/files", files)
http.HandleFunc("/forward", forward)
http.ListenAndServe(":3000", nil)
}