This is a common way to use ioutil.ReadDir, but I often see implementations that use panic or log.Fatal for error handling. In Go, the correct error handling is to return the error to the caller and output the error at an entry point such as main.go.
Therefore, this article introduces an example implementation of correct error handling using ioutil.ReadDir.
As an example, we want to scan a directory with three files, as follow.
mypkg ├── dir_b │ └── file_b ├── dir_c │ └── file_c └── file_a
The point is to call Dirwalk recursively in the case of a directory and search until you reach a leaf (file) in the directory tree. It then merges the paths that reach the leaf into the caller's path one after the other.
We can see that the list of files can be obtained as expected by the following tests.
$ go test -v === RUN TestDirwalk --- PASS: TestDirwalk (0.01s) PASS ok github.com/d-tsuji/go-sandbox/mypkg 0.016s
Here's an example implementation that can retrieve all the files under a directory and handle errors with care. I hope this has been helpful to you.