-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
205 lines (168 loc) · 4.85 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// an extremely fast, zero config server for modern web applications.
package main
import (
"html/template"
"net/http"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"github.com/evanw/esbuild/pkg/api"
"github.com/evanw/esbuild/pkg/cli"
"github.com/osdevisnot/sorvor/pkg/livereload"
"github.com/osdevisnot/sorvor/pkg/logger"
)
type sorvor struct {
buildOptions api.BuildOptions
serveOptions api.ServeOptions
src string
port string
dev bool
}
type npm struct {
Name string `json:"name"`
Version string `json:"version"`
}
var extensions = map[string]string{
".js": ".js",
".ts": ".js",
".jsx": ".js",
".tsx": ".js",
".css": ".css",
}
func readOptions(pkg npm) *sorvor {
var err error
var esbuildArgs []string
osArgs := os.Args[1:]
serv := &sorvor{}
for _, arg := range osArgs {
switch {
case strings.HasPrefix(arg, "--src"):
serv.src = arg[len("--src="):]
case strings.HasPrefix(arg, "--port"):
port, err := strconv.Atoi(arg[len("--port="):])
logger.Fatal(err, "Invalid Port Value")
serv.port = ":" + strconv.Itoa(port)
serv.serveOptions.Port = uint16(port + 1)
case arg == "--dev":
serv.dev = true
default:
esbuildArgs = append(esbuildArgs, arg)
}
}
serv.buildOptions, err = cli.ParseBuildOptions(esbuildArgs)
logger.Fatal(err, "Invalid option for esbuild")
serv.buildOptions.Bundle = true
serv.buildOptions.Write = true
if serv.dev == true && serv.port == "" {
serv.port = ":1234"
serv.serveOptions.Port = uint16(1235)
}
if serv.buildOptions.Outdir == "" {
serv.buildOptions.Outdir = "dist"
}
if serv.src == "" {
serv.src = "src"
}
return serv
}
func readPkg() npm {
pkg := npm{}
// file, err := ioutil.ReadFile("package.json")
// handleError("Unable to read package.json", err, false)
// err = json.Unmarshal(file, &pkg)
// handleError("Unable to parse package.json", err, false)
return pkg
}
func (serv *sorvor) esbuild(entry string) string {
serv.buildOptions.EntryPoints = []string{filepath.Join(serv.src, entry)}
result := api.Build(serv.buildOptions)
var outfile string
for _, file := range result.OutputFiles {
if filepath.Ext(file.Path) != "map" {
cwd, _ := os.Getwd()
outfile = strings.TrimPrefix(file.Path, filepath.Join(cwd, serv.buildOptions.Outdir))
}
}
return outfile
}
func (serv *sorvor) build(pkg npm) []string {
srcIndex := filepath.Join(serv.src, "index.html")
targetIndex := filepath.Join(serv.buildOptions.Outdir, "index.html")
var entries []string
tmpl, err := template.New("index.html").Funcs(template.FuncMap{
"livereload": func() template.JS {
return template.JS(livereload.Snippet)
},
"esbuild": func(entry string) string {
if serv.dev == true {
entries = append(entries, filepath.Join(serv.src, entry))
ext := path.Ext(entry)
outfile := entry[0:len(entry)-len(ext)] + extensions[ext]
return "http://localhost:" + strconv.Itoa(int(serv.serveOptions.Port)) + "/" + outfile
}
return serv.esbuild(entry)
},
}).ParseFiles(srcIndex)
logger.Fatal(err, "Unable to parse index.html")
file, err := os.Create(targetIndex)
logger.Fatal(err, "Unable to create index.html in outdir")
defer file.Close()
err = tmpl.Execute(file, pkg)
logger.Fatal(err, "Unable to execute index.html")
return entries
}
func (serv *sorvor) ServeHTTP(res http.ResponseWriter, request *http.Request) {
res.Header().Set("access-control-allow-origin", "*")
path := filepath.Join(serv.buildOptions.Outdir, filepath.Clean(request.URL.Path))
if stat, err := os.Stat(path); err != nil {
// serve a root index when path is not found
http.ServeFile(res, request, filepath.Join(serv.buildOptions.Outdir, "index.html"))
return
} else if stat.IsDir() {
// serve root index when requested path is a directory
http.ServeFile(res, request, filepath.Join(serv.buildOptions.Outdir, "index.html"))
return
}
// else just serve the file normally...
http.ServeFile(res, request, path)
return
}
func (serv *sorvor) serve(pkg npm) {
serv.buildOptions.EntryPoints = serv.build(pkg)
wg := new(sync.WaitGroup)
wg.Add(2)
// start esbuild server
go func() {
_, err := api.Serve(serv.serveOptions, serv.buildOptions)
if err != nil {
logger.Error(err, "Failed to start esbuild server")
wg.Done()
}
}()
// start our own server
go func() {
logger.Info(logger.BlueText("sørvør"), "ready on", logger.BlueText("http://localhost", serv.port))
liveReload := livereload.New(serv.src)
liveReload.Start()
http.Handle("/livereload", liveReload)
http.Handle("/", serv)
err := http.ListenAndServe(serv.port, nil)
logger.Error(err, "Failed to start http server")
wg.Done()
}()
wg.Wait()
}
func main() {
pkg := readPkg()
serv := readOptions(pkg)
err := os.MkdirAll(serv.buildOptions.Outdir, 0775)
logger.Fatal(err, "Failed to create output directory")
if serv.dev == true {
serv.serve(pkg)
} else {
serv.build(pkg)
}
}