Created
April 6, 2014 19:02
-
-
Save kavu/10010182 to your computer and use it in GitHub Desktop.
One day @gamesbrainiac asked me to make a simple File Watcher on Go…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"os" | |
"path/filepath" | |
"time" | |
) | |
type pathsModTimes map[string]time.Time | |
var paths pathsModTimes | |
func walker(path string, info os.FileInfo, err error) error { | |
var modTime time.Time = info.ModTime() | |
if err != nil { | |
panic(err) | |
} | |
if t, ok := paths[path]; ok { | |
if !modTime.Equal(t) { | |
log.Printf("Something happened with `%s`\n", path) | |
paths[path] = modTime | |
} | |
} else { | |
paths[path] = modTime | |
} | |
return nil | |
} | |
func watcher(path string) { | |
for { | |
select { | |
case <-time.After(1 * time.Second): | |
filepath.Walk(path, walker) | |
} | |
} | |
} | |
func init() { | |
paths = make(pathsModTimes) | |
} | |
func main() { | |
go watcher("data") | |
for { | |
select {} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment