-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve.go
79 lines (60 loc) · 1.41 KB
/
serve.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
package main
import (
"crypto/rand"
"fmt"
"log"
"math/big"
"net/http"
"path"
"github.com/abc-inc/browser"
"github.com/sean9999/fasthak/certs"
gorph "github.com/sean9999/go-fsnotify-recursively"
)
func serve() error {
// watch directory
watcher, _ := gorph.New(fmt.Sprintf("%s/**", *dir))
fsEvents, _ := watcher.Listen()
// braodcast to all cients
sseBroker := NewBroadcaster[gorph.GorphEvent]()
// debounce noisy events
debouncer := debounce(fsEvents)
// broadcsast debounced events
go func() {
for ev := range debouncer.Subscribe() {
if ev.NotifyEvent.Name != "CHMOD" {
fmt.Println(ev)
}
sseBroker.Broadcast(ev)
}
}()
mux := http.NewServeMux()
// static files
staticFileServer := http.FileServer(http.Dir(*dir))
mux.Handle("/", injectHeaders(staticFileServer))
// .hak/js/*
mux.Handle(hakPrefix+"/js/", hakHandler())
// ./hak/fs/sse
mux.Handle(path.Join(hakPrefix, ssePath), sseBroker)
cert, err := certs.KeyPair()
if err != nil {
return err
}
// start server
url := fmt.Sprintf("https://%s.%s:%d", randomSlug(), domain, *port)
fmt.Printf("running on %s", url)
browser.Open(url)
ListenAndServeTLSKeyPair(fmt.Sprintf(":%d", *port), cert, mux)
// if err != nil {
// return nil, err
// }
return nil
}
func randomSlug() string {
n, _ := rand.Int(rand.Reader, big.NewInt(65536))
return fmt.Sprintf("%x", n)
}
func barfOn(e error) {
if e != nil {
log.Fatal(e)
}
}