The Go program introduces a GetDirectorySize function that receives a path string (a folder path) and returns an int64 value indicating the total size.
package main
import (
"fmt"
"os"
)
func GetDirectorySize(folder string) int64 {
// Step 2: read directory and handle errors.
dirRead, err := os.Open(folder)
if err != nil {
panic(err)
}
dirFiles, err := dirRead.Readdir(0)
if err != nil {
panic(err)
}
// Step 3: sum up Size of all files in the directory.
sum := int64(0)
for _, fileHere := range dirFiles {
sum += fileHere.Size()
}
// Step 4: close directory and return the sum.
dirRead.Close()
return sum
}
func main() {
// Step 1: call GetDirectorySize and print size of some directories.
sum1 := GetDirectorySize(
"programs/")
sum2 := GetDirectorySize(
"site/")
fmt.Println(sum1)
fmt.Println(sum2)
}
10514648
277682