-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
101 lines (82 loc) · 1.94 KB
/
main.go
File metadata and controls
101 lines (82 loc) · 1.94 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
package main
import (
"bytes"
_ "embed"
"flag"
"fmt"
"net/http"
"os"
"path/filepath"
)
//go:embed event.js
var eventScript string
type config struct {
addr string
dir string
debug bool
}
func main() {
cfg := config{}
flag.StringVar(&cfg.addr, "addr", ":8080", "network address")
flag.StringVar(&cfg.dir, "dir", ".", "directory to serve from")
flag.BoolVar(&cfg.debug, "debug", false, "verbose logging")
flag.Parse()
if cfg.debug {
logger.level = LevelDebug
}
ps := new(pubsub)
go watchFiles(cfg.dir, ps)
mux := http.NewServeMux()
mux.HandleFunc("/", serveFiles(cfg.dir))
mux.HandleFunc("/events", handleEvents(ps))
logger.Info("Starting server from %#v at %#v", cfg.dir, cfg.addr)
err := http.ListenAndServe(cfg.addr, logRequest(mux))
logger.Error("Failed to start: %s", err)
os.Exit(1)
}
func serveFiles(dir string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
fp := resolveFilepath(dir, r.URL.Path)
if filepath.Ext(fp) == ".html" {
serveHtml(w, r, fp)
} else {
http.ServeFile(w, r, fp)
}
}
}
func handleEvents(ps *pubsub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.(http.Flusher).Flush()
done := r.Context().Done()
ch := ps.subscribe()
defer ps.unsubscribe(ch)
for {
select {
case <-done:
return
case event := <-ch:
fmt.Fprintf(w, "event: change\ndata: %s\n\n", event)
w.(http.Flusher).Flush()
}
}
}
}
// Serve a HTML file with injected <script>
func serveHtml(w http.ResponseWriter, r *http.Request, fp string) {
html, err := os.ReadFile(fp)
if err != nil {
http.NotFound(w, r)
return
}
html = bytes.Replace(
html,
[]byte("</body>"),
[]byte("<script>"+eventScript+"</script></body>"),
1,
)
w.Write(html)
}