如何遍历特定文件夹

I have following directory structure

Root
   |
   |-- dev 
   |     | 
   |     +- files, subdirectory within dev
   |-- prod
   |     |
   |     +- files, subdirectory within prod 
   |-- .git
   |     |
   |     +- .git directory structure
   |--CODEOWNER (file)
   |--README (file)

I want to traverse all files in dev and prod.

I tried doing the following

files, err := ioutil.ReadDir("./")
if err != nil {
    log.Fatal(err)
}

for _, val := range files {
    // To handle codeowner and readme
    if !val.isDir(){
       continue
    }

   // To handle .git
   if val.Name() == ".git"{
     continue
   }
    err := filepath.Walk(val, func(path string, f os.FileInfo, err error) error {
     // Traverse dircectory , subdirectories and files
}

Is there any better way of doing this? My only requirement is "I want to traverse top-level directory(dev and prod) in root directory other than directory starting with a dot(.)

To be more clear:

  • In output I want
    • All files, directories, subdirectories of dev
    • All files, directories, subdirectories of prod
  • what I do not want
    • Any director of root other than dev and prod (like .git)
    • Any files of root (like codeowner or readme)

Use filepath.Glob.

This gets all files in the foo directory, relative to your working directory:

matches, err := filepath.Glob("./foo/*")
if err != nil {
    panic(err.Error())
}

for _, match := range matches {
    fmt.Printf("Got match: %s
", match)
}

Playground

In your case, you'd use filepath.Glob("./dev/*") and filepath.Glob("./prod/*"). Go's implementation doesn't support the "double-star directive" for recursive globs though, so you will have to handle subdirectories yourself.