Skip to content

Instantly share code, notes, and snippets.

@miticojo
Created July 24, 2017 23:44
Show Gist options
  • Save miticojo/985dda5ccb605efb47ed726f8c100774 to your computer and use it in GitHub Desktop.
Save miticojo/985dda5ccb605efb47ed726f8c100774 to your computer and use it in GitHub Desktop.
calculate directory size in GO
package main
import (
"fmt"
"os"
"path/filepath"
"log"
"code.cloudfoundry.org/bytefmt"
)
func DirSize(path string) (uint64, error) {
var size uint64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if !info.IsDir() {
size += uint64(info.Size())
}
return err
})
return size, err
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("usage: %s [directory path]\n", os.Args[0])
os.Exit(1)
}
m, err := DirSize(os.Args[1])
if err != nil {
log.Fatal(err)
}
fmt.Printf(bytefmt.ByteSize(m))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment