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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more