forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (62 loc) · 1.49 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
package main
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/theplant/blackfriday"
"gopkg.in/unrolled/render.v1"
)
var Render = render.New(render.Options{
Layout: "layout",
IsDevelopment: true,
})
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fs := http.FileServer(http.Dir("."))
handler := func(rw http.ResponseWriter, r *http.Request) {
// Render the index as the main readme
if r.URL.Path == "/" {
if err := renderMarkdown(rw, "README.md"); err != nil {
return
}
// Render markdown files
} else if strings.HasSuffix(r.URL.Path, ".md") {
if err := renderMarkdown(rw, r.URL.Path[1:]); err != nil {
return
}
} else if strings.HasSuffix(r.URL.Path, ".go") {
if err := renderCode(rw, r.URL.Path[1:]); err != nil {
return
}
} else {
fs.ServeHTTP(rw, r)
}
}
fmt.Println("Listening on port", port)
http.ListenAndServe(":"+port, http.HandlerFunc(handler))
}
func renderMarkdown(rw http.ResponseWriter, name string) error {
data, err := ioutil.ReadFile(name)
if err != nil {
http.Error(rw, "Unable to read file", 500)
return err
}
output := blackfriday.MarkdownCommon(data)
Render.HTML(rw, 200, "slide", template.HTML(output))
return nil
}
func renderCode(rw http.ResponseWriter, name string) error {
data, err := ioutil.ReadFile(name)
if err != nil {
http.Error(rw, "Unable to read file", 500)
return err
}
Render.HTML(rw, 200, "code", string(data))
return nil
}