Skip to content

Instantly share code, notes, and snippets.

@caojunxyz

caojunxyz/.go

Created Sep 8, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.