-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
69 lines (57 loc) · 1.4 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
package main
import (
"log"
"net/http"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
)
// channel to read reload request
var reloadChan = make(chan bool)
func main() {
// serve the static files
http.Handle("/", http.FileServer(http.Dir("./static")))
// End point for reload notification
http.HandleFunc("/reload", func(w http.ResponseWriter, r *http.Request) {
// Read the incoming request
<-reloadChan
w.Write([]byte("reload")) // sends reload info to /reload route
})
// Concurrent function to watch file changes
go scanFileChanges()
// start the server
log.Println(`Starting the serve at: 8000`)
log.Fatal(http.ListenAndServe(":8000", nil))
}
// scan for file changes
func scanFileChanges() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
// Listen for events
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Println("events:", event)
if event.Op&fsnotify.Write == fsnotify.Write && isTrackedFile(event.Name) {
log.Println("Modified File:", event.Name)
reloadChan <- true
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("Error :", err)
}
}
}
// Check if this is correct file extension or not
func isTrackedFile(fileName string) bool {
ext := strings.ToLower(filepath.Ext(fileName))
return ext == ".html" || ext == ".css" || ext == ".js"
}