Previously, we had been using filepath.WalkDir to walk the directory tree. This worked by walking the file system directly. As a result, we have to make sure that the file system is in the correct state before we can use it. As we have seen, this can cause a lot of setup work to be done. Either we have to keep a completely different folders for each test scenario we have, or we have to create all of the files and folders at the start of the test before we begin. This is a lot of work, and is often error prone.
If we use the fs.WalkDir function, Listing 14.1, instead, which takes, as its first argument, a fs.FS implementation. Instead of walking the file system the fs.FS is walked instead.
In Listing 14.2 we can continue to use the same code inside of the fs.WalkFunc function as we did before. Our test code only needs two small changes now to make it work. The first is we an implementation of the fs.FS interface to pass to the Walk function. For now, we can use the os.DirFS function, Listing 14.3. The implementation will be backed directly by the file system.
File Paths
The other change we need to make is the expected paths. Before, we were expecting paths such as /data/a.txt returned from our Walk function. However, when working with fs.FS implementations, the paths returned are relative to the root of the implementation. In this case, we are using os.DirFS("data") to create the fs.FS implementation. This places data at the root of the file system implementation and paths returned from the Walk function will be relative to this root.
Note: Paths are expected to use / as the path separator, regardless of the operating system.
We need to update our test code to for the relative paths, a.txt, to be returned instead of /data/a.txt.
As we can see from the test output in Listing 14.4, we have successfully updated our code to use the fs.FS interface.