Created
February 8, 2022 00:16
-
-
Save jayalane/08ee11d68d14d7bcda7e2ebc9e015331 to your computer and use it in GitHub Desktop.
Non-Blocking os.ReadDir()
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
// 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