forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (89 loc) · 2.06 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"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") {
// Do we want to run code or render it?
if strings.HasPrefix(r.URL.Path, "/run") {
if err := runCode(rw, r.URL.Path[5:]); err != nil {
log.Println("Error:", err)
}
return
}
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
}
d := struct {
Code string
File string
}{
Code: string(data),
File: name,
}
Render.HTML(rw, 200, "code", d)
return nil
}
func runCode(rw http.ResponseWriter, name string) error {
log.Println("Running file", name)
cmd := exec.Command("go", "run", name)
out, err := cmd.CombinedOutput()
if err != nil {
http.Error(rw, string(out), http.StatusInternalServerError)
return err
}
rw.Write(out)
return nil
}