go 51 lines · 7 steps

Walking a directory tree to find large files in Go

A single WalkDir traversal filters by extension and size while skipping noisy directories.

Explained by highlit
1package fsutil
2 
3import (
4 "io/fs"
5 "os"
6 "path/filepath"
7 "strings"
8)
9 
10type Match struct {
11 Path string
12 Size int64
13}
14 
15func FindLargeFiles(root, ext string, minSize int64) ([]Match, error) {
16 var matches []Match
17 ext = strings.ToLower(ext)
18 
19 err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
20 if err != nil {
21 if os.IsPermission(err) {
22 return nil
23 }
24 return err
25 }
26 
27 if d.IsDir() {
28 name := d.Name()
29 if name == ".git" || name == "node_modules" || name == "vendor" {
30 return filepath.SkipDir
31 }
32 return nil
33 }
34 
35 if ext != "" && !strings.EqualFold(filepath.Ext(path), ext) {
36 return nil
37 }
38 
39 info, err := d.Info()
40 if err != nil {
41 return err
42 }
43 
44 if info.Size() >= minSize {
45 matches = append(matches, Match{Path: path, Size: info.Size()})
46 }
47 return nil
48 })
49 
50 return matches, err
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1filepath.WalkDir drives a recursive traversal through one callback you supply per entry.
  2. 2Returning sentinel values like filepath.SkipDir or nil steers the walk without unwinding the whole traversal.
  3. 3Closing over an accumulator slice lets the callback collect results across the entire tree.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Walking a directory tree to find large files in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code