find the contents of a directory in go

To find the contents of a directory in Go, you first need to import the os and io/ioutil packages. Then, you can use the Readdir method to get a list of all the files and subdirectories in the directory.

main.go
package main

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

func main() {
	dir := "/path/to/directory"
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

	fmt.Println("Files in", dir)
	for _, file := range files {
		fmt.Println(file.Name())
	}
}
285 chars
22 lines

In the example above, replace /path/to/directory with the path to the directory whose contents you want to find. The ReadDir method returns a slice of os.FileInfo objects, which contain information about each file or directory in the folder. In this case, we simply print out the name of each file or directory using a for loop. If there is an error reading the directory, we print the error message and exit the program.

gistlibby LogSnag