-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
196 lines (166 loc) · 4.64 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
// Copyright 2017 Atelier Disko. 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"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"github.com/fatih/color"
isatty "github.com/mattn/go-isatty"
)
var (
// Version string, compiled in.
Version string
// OS Signal channel.
sigc chan os.Signal
// Instance of the design defintions tree.
tree *NodeTree
// Watcher instance overseeing the tree for changes.
watcher *Watcher
// Global instance of a message broker.
broker *MessageBroker
)
func main() {
// Disable prefix, we are invoked directly.
log.SetFlags(0)
isTerminal := isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
// Listen for interrupt and allow to cancel program early.
sigc = make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt)
go func() {
for sig := range sigc {
log.Printf("Caught %v signal, bye!", sig)
log.Print("Cleaning up...")
// Close services in reverse order of starting them. They might
// not yet have been started, if we've been invoked early.
if tree != nil {
tree.Close()
}
if watcher != nil {
watcher.Close()
}
if broker != nil {
broker.Close()
}
os.Exit(1)
}
}()
host := flag.String("host", "127.0.0.1", "host IP to bind to")
port := flag.String("port", "8080", "port to bind to")
noColor := flag.Bool("no-color", false, "disables color output")
flag.Parse()
if len(flag.Args()) > 1 {
log.Fatalf("Too many arguments given, expecting exactly 0 or 1")
}
// Color package automatically disables colors when not a TTY. We
// don't need to check for an interactive terminal here again.
if *noColor {
color.NoColor = true
}
whiteOnBlue := color.New(color.FgWhite, color.BgBlue).SprintFunc()
green := color.New(color.FgGreen).SprintFunc()
red := color.New(color.FgRed).SprintFunc()
if isTerminal {
log.Print(whiteOnBlue(" DSK "))
log.Printf("Version %s", Version)
log.Print()
}
log.Print("Starting message broker...")
broker = NewMessageBroker() // assign to global
broker.Start()
log.Printf("Detecting tree root...")
here, err := detectRoot(os.Args[0], flag.Arg(0))
if err != nil {
log.Fatalf("Failed to detect root of design definitions tree: %s", red(err))
}
log.Printf("Tree root found: %s", here)
PrettyPathRoot = here
log.Print("Begin watching tree for changes...")
w := NewWatcher(here)
if err := w.Open(IgnoreNodesRegexp); err != nil {
log.Fatalf("Failed to install watcher: %s", red(err))
}
watcher = w // assign to global
log.Print("Opening tree...")
tree = NewNodeTree(here, watcher, broker) // assign to global
if err := tree.Open(); err != nil {
log.Fatalf("Failed to open tree: %s", red(err))
}
log.Print("Mounting APIv1...")
apiv1 := NewAPIv1(tree, broker)
apiv1.MountHTTPHandlers()
// Handles frontend root document delivery and frontend assets.
log.Print("Mounting frontend...")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if filepath.Ext(r.URL.Path) != "" {
assetHandler(w, r)
} else {
rootHandler(w, r)
}
})
addr := fmt.Sprintf("%s:%s", *host, *port)
log.Printf("Starting web interface on %s....", addr)
if isTerminal {
log.Print()
log.Printf("Please visit: %s", green("http://"+addr))
log.Print("Hit Ctrl+C to quit")
log.Print()
}
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatalf("Failed to start web interface: %s", red(err))
}
}
// Serves the frontend's index.html.
//
// Handles these kinds of URLs:
// /
// /index.html
// /* <catch all>
func rootHandler(w http.ResponseWriter, r *http.Request) {
wr := &HTTPResponder{w, r, ""}
path := "index.html"
// Does not check on path, as we only ever serve a single
// file from here, and that path is hard-coded.
buf, err := Asset(path)
if err != nil {
wr.Error(HTTPErrNoSuchAsset, err)
return
}
info, err := AssetInfo(path)
if err != nil {
wr.Error(HTTPErr, err)
return
}
http.ServeContent(w, r, info.Name(), info.ModTime(), bytes.NewReader(buf))
}
// Serves the frontend's assets.
//
// Handles these kinds of URLs:
// /assets/css/base.css
// /static/css/main.41064805.css
func assetHandler(w http.ResponseWriter, r *http.Request) {
wr := &HTTPResponder{w, r, ""}
path := r.URL.Path[len("/"):]
if err := checkSafePath(path, tree.path); err != nil {
wr.Error(HTTPErrUnsafePath, err)
return
}
buf, err := Asset(path)
if err != nil {
wr.Error(HTTPErrNoSuchAsset, err)
return
}
info, err := AssetInfo(path)
if err != nil {
wr.Error(HTTPErr, err)
return
}
http.ServeContent(w, r, info.Name(), info.ModTime(), bytes.NewReader(buf))
}