Skip to content

Instantly share code, notes, and snippets.

@caojunxyz
Created September 8, 2019 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caojunxyz/25459b227a10cf1cfd8568c42bc766a4 to your computer and use it in GitHub Desktop.
Save caojunxyz/25459b227a10cf1cfd8568c42bc766a4 to your computer and use it in GitHub Desktop.
Two methods of traverse directory with golang
func exclude(dir, path string) bool {
rel, _ := filepath.Rel(dir, path)
segs := strings.Split(rel, fmt.Sprintf("%c", os.PathSeparator))
if segs[0] == ".git" || segs[0] == ".idea" {
return true
}
name := filepath.Base(path)
if name == ".DS_Store" {
return true
}
return false
}
func getFileList(dir string) []string {
list := make([]string, 0)
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if exclude(dir, path) {
return nil
}
list = append(list, path)
return nil
})
return list
}
func readDirAll(dir string) []string {
list := make([]string, 0)
var f func(string, string)
f = func(root string, rel string) {
files, err := ioutil.ReadDir(filepath.Join(root, rel))
if err != nil {
panic(err)
}
for _, file := range files {
if file.IsDir() {
f(root, filepath.Join(rel, file.Name()))
continue
}
path := filepath.Join(root, rel, file.Name())
if exclude(root, path) {
continue
}
list = append(list, path)
}
}
f(dir, ".")
return list
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment