loading...

How to get filepath recursively in Go

tutuz profile image Tsuji Daishiro ・1 min read

Introduction

You sometimes want to get a list of the filepath in directory. One of the ways to achieve shell find-like behavior in Go is to use ioutil.ReadDir. Another way is to use filepath.Walk.

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.

Implementation

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
  • dir.go

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.

  • dir_test.go

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

Summary

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.

Posted on by:

Discussion

markdown guide