Skip to content

Commit

Permalink
Add optional debounce parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
romshark committed Jun 13, 2021
1 parent 5aec3bf commit 6ced243
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/romshark/watchserve
go 1.16

require (
github.com/bep/debounce v1.2.0
github.com/fsnotify/fsnotify v1.4.9
github.com/pkg/browser v0.0.0-20210606212950-a7b7a6107d32
github.com/r3labs/sse/v2 v2.3.3
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/bep/debounce v1.2.0 h1:wXds8Kq8qRfwAOpAxHrJDbCXgC5aHSzgQb/0gKsHQqo=
github.com/bep/debounce v1.2.0/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
Expand Down
18 changes: 14 additions & 4 deletions serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import (
"net/http"
"os"
"sync"
"time"

_ "embed"

"github.com/bep/debounce"
"github.com/fsnotify/fsnotify"
"github.com/pkg/browser"
sse "github.com/r3labs/sse/v2"
Expand All @@ -21,6 +23,7 @@ var frameHTML []byte
func main() {
fFilePath := flag.String("f", "", "file path")
fHost := flag.String("host", "127.0.0.1:8080", "host address")
fDebounce := flag.Duration("debounce", 0, "debounce duration")
flag.Parse()

if *fFilePath == "" {
Expand All @@ -39,7 +42,7 @@ func main() {
var wg sync.WaitGroup
wg.Add(1)

go watchFile(*fFilePath, sseSrv, "updates")
go watchFile(*fFilePath, sseSrv, "updates", *fDebounce)
go listenHTTP(*fHost, *fFilePath, fileContents, sseSrv)

{
Expand All @@ -57,6 +60,7 @@ func watchFile(
filePath string,
sseSrv *sse.Server,
streamUpdates string,
debounceDur time.Duration,
) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
Expand All @@ -68,16 +72,22 @@ func watchFile(
}

var updateMsgWrite = []byte("write")
publishEvent := func() {
sseSrv.Publish(streamUpdates, &sse.Event{
Data: updateMsgWrite,
})
}

debounced := debounce.New(debounceDur)

for {
select {
case e := <-watcher.Events:
if e.Name != filePath || e.Op == fsnotify.Write {
continue
}
log.Print("file change detected")
sseSrv.Publish(streamUpdates, &sse.Event{
Data: updateMsgWrite,
})
debounced(publishEvent)
case err := <-watcher.Errors:
log.Fatal("watching file:", err)
}
Expand Down

0 comments on commit 6ced243

Please sign in to comment.