sequential.dev

Code snippet - Listing files recursively

articlegoprogramming

Just a quick excerpt to show my appreciation for Go.
Quick + intuitive code that you can write and run in seconds always wins.

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func main() {
	RecursiveDirectoryCrawl("dir-name")
}

func RecursiveDirectoryCrawl(dirName string) {
	files, err := ioutil.ReadDir(dirName)
	handleError(err)

	for _, f := range files {
		fileOrDir, err := os.Stat(dirName + "/" + f.Name())
		handleError(err)
		switch mode := fileOrDir.Mode(); {
		case mode.IsDir():
			RecursiveDirectoryCrawl(dirName + "/" + f.Name())
		case mode.IsRegular():
			s := strings.Split(f.Name(), ".")
				handleError(err)
			  fmt.Println(dirName+ "/" +f.Name())
		}
	}
}

func handleError(e error) {
	if e != nil {
		panic(e)
	}
}

This snippet, when pointed at a directory, will print out files in the directory, as well as it's subdirectories, while ignoring the folders.