Skip to content

Instantly share code, notes, and snippets.

@moongears
Created August 17, 2014 06:13
Show Gist options
  • Save moongears/f1f2eec925997502a755 to your computer and use it in GitHub Desktop.
Save moongears/f1f2eec925997502a755 to your computer and use it in GitHub Desktop.
Golang filepath.Walk sample
package main
import (
"fmt"
"os"
"path"
"path/filepath"
)
func main() {
gopath := os.Getenv("GOPATH")
fmt.Printf("[%s/bin]\n", gopath)
list := getShellScript(gopath)
for i, p := range list {
fmt.Printf("[%d:%s===%s]\n", i, path.Dir(p), path.Base(p))
}
}
func getShellScript(rootpath string) []string {
list := make([]string, 0, 10)
err := filepath.Walk(rootpath, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if filepath.Ext(path) == ".sh" {
list = append(list, path)
}
return nil
})
if err != nil {
fmt.Printf("walk error [%v]\n", err)
}
return list
}
@bokunodev
Copy link

i think

if info.IsDir() {
         return nil
}

is unnecessary

@d3rrick
Copy link

d3rrick commented Aug 25, 2020

Nice Stuff, Though noted something, Inside filepath.Walk function, begin by checking error, else you will get panics incase the directory is invalid or not found,

err := filepath.Walk(rootpath, func(path string, info os.FileInfo, err error) error {
if err != nil {
	fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err)
	return err
}

_**// do stuffs here ..**_
return nil
})

as described here,WalkFunc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment