Skip to content

Instantly share code, notes, and snippets.

@jayalane
Created February 8, 2022 00:16
Show Gist options
  • Save jayalane/08ee11d68d14d7bcda7e2ebc9e015331 to your computer and use it in GitHub Desktop.
Save jayalane/08ee11d68d14d7bcda7e2ebc9e015331 to your computer and use it in GitHub Desktop.
Non-Blocking os.ReadDir()
// readDir reads the directory and returns the list
// it uses a little separate go-routine in order to handle timeouts
func (s scannerApp) readDir(d string) ([]os.DirEntry, error) {
ch := make(chan []os.DirEntry, 2)
go func(d string) {
deList, err := os.ReadDir(d)
if err != nil {
ml.La("ReadDir got Error", err)
count.IncrSuffix("dir-read-err", s.file)
ch <- []os.DirEntry{}
return
}
ch <- deList
}(d)
select {
case deList := <-ch:
if len(deList) == 0 {
return nil, errors.New("No Directory List")
}
return deList, nil
case <-time.After(3600 * time.Second):
count.Incr("dir-read-timeout")
return nil, errors.New("Dir Read Timeout")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment