DEV Community

Masui Masanori
Masui Masanori

Posted on

[Go] Generate File Tree

#go

[Go] Generate File Tree

Intro

This time, I try getting files and sub directories from the root directory.

Image description

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)