Skip to content

Instantly share code, notes, and snippets.

@tannerjfco
Created April 5, 2017 23:11
Show Gist options
  • Save tannerjfco/8d0389e4b239912e84d7f2eba2e25e50 to your computer and use it in GitHub Desktop.
Save tannerjfco/8d0389e4b239912e84d7f2eba2e25e50 to your computer and use it in GitHub Desktop.
golang FindFileByExtension
// FindFileByExtension walks a given directory searching for a given extension and returns a list of matching results.
func FindFileByExtension(dirpath string, ext string) ([]string, error) {
var match []string
err := filepath.Walk(dirpath, func(path string, f os.FileInfo, _ error) error {
if !f.IsDir() && strings.HasSuffix(f.Name(), ext) {
match = append(match, f.Name())
}
return nil
})
if err != nil {
return []string{}, err
}
if len(match) < 1 {
return match, fmt.Errorf("no %s files found in %s", ext, dirpath)
}
return match, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment