-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
107 lines (85 loc) · 2.32 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
107
// Copyright 2014 Joseph Hager. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"flag"
"fmt"
"github.com/shurcool/gopherjslib"
"io/ioutil"
"net/http"
"os"
"path"
)
const failure = `<html><head><title>SRVi</title></head><body style="color:#555555;background:#ffeedd;font-family:Arial;font-size:20px;margin:75px;">%s</body></html>`
var success = `<html><head><title>SRVi</title></head><body><script src="/app.go.js" type="text/javascript"></script></body></html>`
var index *string
var code = ""
func buildHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" && r.URL.Path != "/index.html" {
http.ServeFile(w, r, r.URL.Path[1:])
return
}
var out bytes.Buffer
builder := gopherjslib.NewBuilder(&out, nil)
names := []string{"main.go"}
if flag.NArg() > 0 {
names = flag.Args()
}
for _, name := range names {
if path.Ext(name) != ".go" {
continue
}
file, err := os.Open(name)
if err != nil {
fmt.Fprintf(w, failure, err)
return
}
defer file.Close()
builder.Add(name, file)
}
if err := builder.Build(); err != nil {
fmt.Fprintf(w, failure, err)
return
}
code = out.String()
if *index != "" {
data, err := ioutil.ReadFile(*index)
if err != nil {
fmt.Fprintf(w, failure, err)
return
}
fmt.Fprint(w, string(data))
} else {
fmt.Fprint(w, success)
}
}
func main() {
index = flag.String("index", "", "The html file to use as an index")
endpoint := flag.String("endpoint", "app.go.js", "The name of the compiled javascript file")
host := flag.String("http", "localhost:8080", "The host at which to serve")
banner := ` _______ _ ___
/ __/ _ \ | / (_)
_\ \/ , _/ |/ / /
/___/_/|_||___/_/ says...
`
flag.Usage = func() {
fmt.Fprintln(os.Stderr, banner)
fmt.Fprintln(os.Stderr, "List your go files as arguments!")
flag.PrintDefaults()
}
flag.Parse()
http.HandleFunc("/", buildHandler)
http.HandleFunc("/"+*endpoint, func(w http.ResponseWriter, r *http.Request) {
w.Header()["Content-Type"] = []string{"text/javascript"}
fmt.Fprint(w, code)
})
fmt.Println(banner)
fmt.Printf("Open your browser to http://%s!\n", *host)
err := http.ListenAndServe(fmt.Sprintf("%s", *host), nil)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
}