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
|
package main
import (
"os"
"strings"
"net/http"
log "github.com/sirupsen/logrus"
md "github.com/russross/blackfriday/v2"
)
func ServeForbidden(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(403);
w.Write([]byte("403 forbidden"));
}
func ServeNotFound(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r);
}
func RenderMarkdown(path string) ([]byte, error) {
data, err := os.ReadFile(path);
if err != nil {
return []byte{}, err;
}
return md.Run(data), nil;
}
func ServeMarkdown(w http.ResponseWriter, r *http.Request, path string) (int, error) {
page, err := RenderMarkdown(path);
if err != nil {
return 404, err;
}
w.WriteHeader(200);
w.Write(page);
return 200, nil;
}
func ServeFile(w http.ResponseWriter, r *http.Request, path string) (int, error) {
if strings.Contains(r.URL.Path, "..") {
// reject requests with ".." in the URL
return 403, nil;
}
data, err := os.ReadFile(path);
if err != nil {
return 404, err;
}
w.WriteHeader(200);
w.Write(data);
return 200, nil;
}
func IsMarkdown(path string) bool {
return strings.HasSuffix(path, ".md");
}
func Serve(w http.ResponseWriter, r *http.Request, path string) {
var status int;
var err error;
if IsMarkdown(path) {
// render and serve markdown content
status, err = ServeMarkdown(w, r, path);
} else {
// serve raw file
status, err = ServeFile(w, r, path);
}
if status == 200 {
log.Infof(
"%v 200\t%v <- %v",
r.Method, r.RemoteAddr, r.URL.Path,
);
} else {
log.Errorf(
"%v %v\t%v <- %v: %v",
r.Method, status, r.RemoteAddr, r.URL.Path, err,
);
switch status {
case 403:
ServeForbidden(w, r);
case 404:
ServeNotFound(w, r);
default:
w.WriteHeader(status);
w.Write([]byte("error"));
}
}
}
|