-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
60 lines (55 loc) · 1.14 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
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"time"
"github.com/fsnotify/fsnotify"
"github.com/mazzegi/gompdf"
)
func main() {
source := flag.String("source", "../../samples/doc2.xml", "")
target := flag.String("target", "doc2.pdf", "")
flag.Parse()
logf("run watcher (source:%s) (target:%s)", *source, *target)
watch, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
err = watch.Add(*source)
if err != nil {
panic(err)
}
exec := func() {
logf("parse and build ...")
err := gompdf.ParseAndBuild(*source, *target)
if err != nil {
logf("ERROR: %v", err)
return
}
logf("parse and build ... done")
}
notC := make(chan os.Signal)
signal.Notify(notC, os.Interrupt, os.Kill)
go func() {
select {
case <-notC:
logf("stop watcher")
watch.Close()
return
}
}()
exec()
lastEvtTime := time.Now()
for evt := range watch.Events {
if evt.Op == fsnotify.Write && time.Since(lastEvtTime) > 200*time.Millisecond {
time.AfterFunc(100*time.Millisecond, exec)
lastEvtTime = time.Now()
}
}
logf("watcher stopped")
}
func logf(format string, args ...interface{}) {
fmt.Printf(format+"\n", args...)
}