DEV Community

Masui Masanori
Masui Masanori

Posted on

[Go] Generate File Tree


[Go] Generate File Tree


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.

Enter fullscreen mode Exit fullscreen mode

Because I don't want to reproduce the folder structure myself, I will use "os.ReadDir".



package main

type FileProps struct {
    Name         string
    RelativePath string
    IsDir        bool
    Children     []FileProps
Enter fullscreen mode Exit fullscreen mode


package main

import (

func main() {
    readDirResult, err := readDir("/home/example/go")
    if err != nil {
    readDirResultData, _ := json.Marshal(readDirResult)

    file, _ := os.Create("readdirresult.json")

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)