-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
267 lines (212 loc) · 4.59 KB
/
Copy pathmain.go
File metadata and controls
267 lines (212 loc) · 4.59 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package main
/* ____ __
___/ / /_/ /____
/ _ / __/ __/ _ \
\_,_/\__/\__/ .__/
/*/
import (
"bytes"
"fmt"
"log/slog"
"net/http"
"net/url"
"os"
"sync"
_ "embed"
flag "github.com/spf13/pflag"
"github.com/zbrd/usage"
)
// Globals
// -------
var (
empty bytes.Reader
prog usage.Program
version = "v0.0.0-dev"
data = []byte("data:\n\n")
opts = &Options{
Addr: ":8000",
Path: ".",
}
bus = &Bus{
su: make(map[int]Sub),
}
info = usage.Data{
"Author": "Zaim B.",
"Contact": "zbrd@duck.com",
"Version": version,
}
)
//go:embed refresh.js
var refreshJs []byte
//go:embed usage.txt
var usageTpl string
//go:embed version.txt
var versionTpl string
// Types
// -----
// Program options
type Options struct {
Addr string
Path string
DoRefresh bool
ShowUsage bool
ShowVersion bool
}
// Sub is a subscription to a Bus.
type Sub struct {
Id int
Events chan struct{}
}
// Bus is a single-topic event bus.
type Bus struct {
id int
su map[int]Sub
mu sync.RWMutex
}
func (b *Bus) Sub() Sub {
b.mu.Lock()
defer b.mu.Unlock()
sub := Sub{
Id: b.id + 1,
Events: make(chan struct{}),
}
b.id = sub.Id
b.su[b.id] = sub
slog.Debug("Bus.Sub()", "id", sub.Id)
return sub
}
func (b *Bus) Unsub(sub Sub) {
b.mu.Lock()
defer b.mu.Unlock()
slog.Debug("Bus.Unsub()", "id", sub.Id)
close(sub.Events)
delete(b.su, sub.Id)
sub.Events = nil
}
func (b *Bus) Pub() {
b.mu.RLock()
defer b.mu.RUnlock()
slog.Debug("Bus.Pub()", "count", len(b.su))
for _, sub := range b.su {
select {
case sub.Events <- struct{}{}:
}
}
}
// Main
// ----
func init() {
prog = usage.Prog(flag.CommandLine)
flag.Usage = showUsage
flag.CommandLine.SetOutput(os.Stdout)
flag.StringVarP(&opts.Addr, "addr", "a", opts.Addr, "")
flag.StringVarP(&opts.Path, "dir", "d", opts.Path, "")
flag.BoolVarP(&opts.DoRefresh, "refresh", "R", false, "")
flag.BoolVarP(&opts.ShowUsage, "help", "h", false, "")
flag.BoolVarP(&opts.ShowVersion, "version", "v", false, "")
flag.Lookup("addr").Usage = "Listen at `ADDR`"
flag.Lookup("dir").Usage = "Serve directory `DIR`"
flag.Lookup("refresh").Usage = "Send refresh event"
flag.Lookup("help").Usage = "Show help information"
flag.Lookup("version").Usage = "Show version information"
}
func main() {
flag.Parse()
switch {
case opts.ShowUsage:
showUsage()
return
case opts.ShowVersion:
showVersion()
return
case opts.DoRefresh:
doRefresh()
return
}
dir := http.Dir(opts.Path)
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(dir))
mux.HandleFunc("/_/events", handleEvents)
mux.HandleFunc("/_/refresh.js", handleRefreshJS)
mux.HandleFunc("POST /_/refresh", handleRefresh)
h := withLogger(mux)
slog.Info(
"Server Listening.",
"addr", opts.Addr,
"path", opts.Path,
)
if err := http.ListenAndServe(opts.Addr, h); err != nil {
slog.Error("Failed to listen and serve.", "err", err)
os.Exit(1)
}
}
func showUsage() {
if err := prog.PrintUsage(usageTpl, info); err != nil {
die("print usage.", err)
}
}
func showVersion() {
if err := prog.PrintUsage(versionTpl, info); err != nil {
die("print version.", err)
}
}
func doRefresh() {
var uri string
if u, err := url.Parse("http://" + opts.Addr); err != nil {
die("parse address", err)
} else {
uri = u.JoinPath("/_/refresh").String()
}
if _, err := http.Post(uri, "text/plain", &empty); err != nil {
die("send refresh event.", err)
}
}
// Handlers
// --------
func handleEvents(w http.ResponseWriter, r *http.Request) {
sub := bus.Sub()
defer bus.Unsub(sub)
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
done := r.Context().Done()
ctrl := http.NewResponseController(w)
for {
select {
case <-done:
slog.Debug("handleEvents request done.")
return
case <-sub.Events:
if _, err := w.Write(data); err != nil {
slog.Error("handleEvents write error.", "err", err)
}
if err := ctrl.Flush(); err != nil {
slog.Error("handleEvents flush error.", "err", err)
}
}
}
}
func handleRefreshJS(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/javascript")
w.Write(refreshJs)
}
func handleRefresh(w http.ResponseWriter, r *http.Request) {
bus.Pub()
w.WriteHeader(204)
}
// Funcs
// -----
func die(op string, err any) {
fmt.Fprintf(os.Stderr, "Failed to %s: %s", op, err)
os.Exit(1)
}
func withLogger(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
slog.Info(
"Request",
"method", r.Method,
"uri", r.URL.Path,
)
h.ServeHTTP(w, r)
}
}