/
app_handler.go
100 lines (84 loc) · 1.89 KB
/
app_handler.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
package kellegous
import (
"bytes"
"fmt"
"io"
"net/http"
"path"
"path/filepath"
"os"
"strings"
)
const (
scriptFileExtension = ".js"
)
type appHandler struct {
root http.Dir
server http.Handler
}
func NewAppHandler(root http.Dir) http.Handler {
return &appHandler{root, http.FileServer(root)}
}
func expandPath(fs http.Dir, name string) string {
return filepath.Join(string(fs), filepath.FromSlash(path.Clean("/"+name)))
}
func expandSource(w http.ResponseWriter, filename string) error {
// output pipe
rp, wp, err := os.Pipe()
if err != nil {
return err
}
defer wp.Close()
defer rp.Close()
cppPath := "/usr/bin/cpp"
p, err := os.StartProcess(cppPath,
[]string{cppPath, "-P", filename},
&os.ProcAttr{
"",
os.Environ(),
[]*os.File{nil, wp, os.Stderr},
nil})
if err != nil {
return err
}
// we won't be writing this any more.
wp.Close()
var b bytes.Buffer
io.Copy(&b, rp)
rp.Close()
s, err := p.Wait(0)
if err != nil {
return err
}
w.Header().Set("Content-Type", "text/javascript")
if s.WaitStatus.ExitStatus() == 0 {
fmt.Fprintln(w, b.String())
} else {
http.Error(w, "processor go boom", 500)
}
return nil
}
func (f *appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
target := expandPath(f.root, r.URL.Path)
// if the file exists, just serve it.
if _, err := os.Stat(target); err == nil {
f.server.ServeHTTP(w, r)
return
}
// if the missing file isn't a special one, 404.
if !strings.HasSuffix(r.URL.Path, scriptFileExtension) {
http.NotFound(w, r)
return
}
source := target[0:len(target)-len(scriptFileExtension)] + ".c.js"
// Make sure the source exists.
if _, err := os.Stat(source); err != nil {
http.NotFound(w, r)
return
}
// handle the special file.
err := expandSource(w, source)
if err != nil {
panic(err)
}
}