Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

go - How to return a directory structure as a complete tree?

I have a directory structure like this:

reports
├── bar
│?? └── 2021-01-25
└── foo
    └── 2021-01-25

I am new to go and try to use the Walk function,

Now I have this code

func FilePathWalkDir(root string) ([]string, error) {
    var files []string
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if info.IsDir() {
            if info.IsDir() && info.Name() == "pages" || info.Name() == "data" || info.Name() == "logs" {
                return filepath.SkipDir
            }
            files = append(files, path)
        }
        return nil
    })
    return files, err
}

And using this like:

func serve(w http.ResponseWriter, r *http.Request) {

    lines := []string{}
    files, err := FilePathWalkDir("reports/")

    if err != nil {
        panic(err)
    }
    for _, file := range files {
        lines = append(lines, file)
    }

    output, err := json.Marshal(lines)
    if err != nil {
        log.Fatal(err)
    }
    w.Header().Set("Content-Type", "application/json")
    //fmt.Println(string(jsonData))
    fmt.Fprintf(w, string(output))
}

And I get this

"reports/"
"reports/bar"
"reports/bar/2021-01-25"
"reports/foo"
"reports/foo/2021-01-25"

But want this:

"reports/bar/2021-01-25"
"reports/foo/2021-01-25"

But I only want to return the last bit (reports/foo/2021-01-27) for each directory - with the dates, and it could be many different dates, like it could be many different project names (foo, bar, barfoo, foobar etc).

Could anyone point me in the right direction?

question from:https://stackoverflow.com/questions/65946292/how-to-return-a-directory-structure-as-a-complete-tree

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you only want paths with dates, why not check to see if the suffix matches that pattern using Regex before appending?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...