Skip to content

Instantly share code, notes, and snippets.

@GwynethLlewelyn
Created March 6, 2023 18:37
Show Gist options
  • Save GwynethLlewelyn/95ffcb266c3bcb6423ac586d309dbd0f to your computer and use it in GitHub Desktop.
Save GwynethLlewelyn/95ffcb266c3bcb6423ac586d309dbd0f to your computer and use it in GitHub Desktop.
How to walk through a directory in Go (using the 'modern' post-1.16 functionality)
// See this in action: https://go.dev/play/p/mA3RRGhyZRe
// Read more about it: https://bitfieldconsulting.com/golang/filesystems#generalising-the-file-counter (scroll down a bit)
//
// The following code excerpt is placed in the Public Domain (CC0) by Gwyneth Llewelyn (2023)
package main
import (
"fmt"
"io/fs"
"os"
)
func main() {
var entries []string
root := "." // valid path, current working directory (wherever that might be)
//root := "fakedir" // valid path, but directory doesn't exist
//root := "../.../aa..us~\\\r" // invalid path
fmt.Printf("[list of files] root is %q\n", root)
if !fs.ValidPath(root) {
entries = append(entries, "[Invalid path <"+root+">!]")
} else {
fileSystem := os.DirFS(root)
dirEntries, err := fs.ReadDir(fileSystem, ".")
if err != nil {
entries = append(entries, "[Error reading directory <"+root+">]: "+err.Error())
} else {
// we've got to assemble all entries in a simple directory entry until I fix the template
for entry := range dirEntries {
if dirEntries[entry].IsDir() {
entries = append(entries, "[DIR] "+dirEntries[entry].Name())
} else {
entries = append(entries, dirEntries[entry].Name())
}
}
}
}
fmt.Printf("[list of files] entries are %#v\n", entries)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment