This is a self-teaching implementation to get files for a given directory in order to simplify os.Walk in Go (avoid to pass a func for recursively walking across the files and directories).
I'm pretty new to the language and feel there is already something wrong with the way the structure ""implements"" the interface. I feel that it should not be by value but rather by reference in order to avoid redundant copies, should it?
package main
import (
"os"
"fmt"
"path/filepath"
"time"
)
type FileDetail interface {
Path() string
Info() os.FileInfo
}
type fileDetail struct{
path string
info os.FileInfo
}
func (detail fileDetail) Path() string {
return detail.path
}
func (detail *ileDetail) Info() os.FileInfo {
return detail.info
}
func GetFiles(path string) []FileDetail {
var details []FileDetail
walkFunc := func (filePath string, fileInfo os.FileInfo, err error) error {
if err != nil {
return err
}
if !fileInfo.IsDir() {
var detail FileDetail = fileDetail{path: filePath, info: fileInfo}
details = append(details, detail)
}
return nil
}
filepath.Walk(path, walkFunc)
return details
}
func GetDirectories(path string) []FileDetail {
var details []FileDetail
walkFunc := func (filePath string, fileInfo os.FileInfo, err error) error {
if err != nil {
return err
}
if fileInfo.IsDir() {
var detail FileDetail = fileDetail{path: filePath, info: fileInfo}
details = append(details, detail)
}
return nil
}
filepath.Walk(path, walkFunc)
return details
}
func main() {
sandBoxDirectory := "F:/Perforce/eperret/XLC/R6Code/framework/source/scimitar/onlinemodule/Sandbox"
time.Now()
files := GetFiles(sandBoxDirectory)
for index, file := range files {
fileInfo := file.Info()
fmt.Println(index, file.Path())
fmt.Println(index, fileInfo.Name(), fileInfo.Size())
}
}