[Go] Generate File Tree
Intro
This time, I try getting files and sub directories from the root directory.
I also can use "filepath.Walk" to get directories and files.
But it returns paths like below.
/home/example/go/pkg/mod/cache/download/golang.org/x/xerrors
Because I don't want to reproduce the folder structure myself, I will use "os.ReadDir".
Samples
FileProps.go
package main
type FileProps struct {
Name string
RelativePath string
IsDir bool
Children []FileProps
}
main.go
package main
import (
"encoding/json"
"log"
"os"
"path/filepath"
)
func main() {
readDirResult, err := readDir("/home/example/go")
if err != nil {
log.Fatal(err.Error())
}
readDirResultData, _ := json.Marshal(readDirResult)
file, _ := os.Create("readdirresult.json")
file.Write(readDirResultData)
file.Close()
}
func readDir(rootDir string) (FileProps, error) {
result := FileProps{
Name: rootDir,
RelativePath: "[ROOT_DIR]",
IsDir: true,
}
err := addChildPropsByReadDir(rootDir, result.RelativePath, &result)
return result, err
}
func addChildPropsByReadDir(baseDir string, relativeDir string, parent *FileProps) error {
files, err := os.ReadDir(baseDir)
if err != nil {
return err
}
parent.Children = make([]FileProps, len(files))
for i, f := range files {
parent.Children[i].Name = f.Name()
if f.IsDir() {
parent.Children[i].IsDir = true
parent.Children[i].RelativePath = filepath.Join(relativeDir, parent.Children[i].Name)
addChildPropsByReadDir(filepath.Join(baseDir, parent.Children[i].Name), parent.Children[i].RelativePath, &parent.Children[i])
} else {
parent.Children[i].IsDir = false
parent.Children[i].RelativePath = relativeDir
}
}
return nil
}
Top comments (0)