I'm trying to extract the directory hierarchy of a folder into a datastructure in go language. filepath.Walk
seems to be the way to go but all I can do so far is to print the names of files and folders. Here's what I'm using:
func main() {
visit := func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
fmt.Println("dir: ", path)
} else {
fmt.Println("file: ", path)
}
return nil
}
err := filepath.Walk("./", visit)
if err != nil {
log.Fatal(err)
}
}
this prints the names of folders like:
dir: folder1
file: folder1/file1.txt
file: folder1/file2.txt
file: folder1/file3.txt
file: folder1/file4.txt
dir: folder1/folder2
file: folder1/folder2/file5.txt
file: folder1/folder2/file6.txt
file: folder1/folder2/file7.txt
file: folder1/folder2/file8.txt
file: folder1/folder2/file9.txt
for tree structure I thought about using something like:
type File struct {
Name string
Content string
}
type Folder struct {
Name string
Files []File
Folders []Folder
}
but of course any suggestions are welcomed.
How can I convert this to a tree structure in go? Is there an easier way to do this?