-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmarkdir.go
78 lines (63 loc) · 1.62 KB
/
markdir.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 (
"errors"
"flag"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"github.com/russross/blackfriday"
)
var bind = flag.String("bind", "127.0.0.1:19000", "port to run the server on")
func main() {
flag.Parse()
httpdir := http.Dir(".")
handler := renderer{httpdir, http.FileServer(httpdir)}
log.Println("Serving on http://" + *bind)
log.Fatal(http.ListenAndServe(*bind, handler))
}
var outputTemplate = template.Must(template.New("base").Parse(`
<html>
<head>
<title>{{ .Path }}</title>
</head>
<body>
{{ .Body }}
</body>
</html>
`))
type renderer struct {
d http.Dir
h http.Handler
}
func (r renderer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if !strings.HasSuffix(req.URL.Path, ".md") && !strings.HasSuffix(req.URL.Path, "/guide") {
r.h.ServeHTTP(rw, req)
return
}
// net/http is already running a path.Clean on the req.URL.Path,
// so this is not a directory traversal, at least by my testing
var pathErr *os.PathError
input, err := ioutil.ReadFile("." + req.URL.Path)
if errors.As(err, &pathErr) {
http.Error(rw, http.StatusText(http.StatusNotFound)+": "+req.URL.Path, http.StatusNotFound)
log.Printf("file not found: %s", err)
return
}
if err != nil {
http.Error(rw, "Internal Server Error: "+err.Error(), 500)
log.Printf("Couldn't read path %s: %v (%T)", req.URL.Path, err, err)
return
}
output := blackfriday.MarkdownCommon(input)
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
outputTemplate.Execute(rw, struct {
Path string
Body template.HTML
}{
Path: req.URL.Path,
Body: template.HTML(string(output)),
})
}