-
Notifications
You must be signed in to change notification settings - Fork 8
/
tmp.go
50 lines (45 loc) · 849 Bytes
/
tmp.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
package kak
import (
"io/ioutil"
"log"
"os"
"github.com/fsnotify/fsnotify"
)
func ReadTmp(tmp *os.File, c chan string) {
// create a watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
// add file to watch
err = watcher.Add(tmp.Name())
if err != nil {
log.Fatal(err)
}
// while we don't get the value
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
// if file written, read it, send to chan and close/clean
if event.Op&fsnotify.Write == fsnotify.Write {
dat, err := ioutil.ReadFile(tmp.Name())
if err != nil {
log.Fatal(err)
}
c <- string(dat)
watcher.Close()
tmp.Close()
os.Remove(tmp.Name())
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}