//go:build linux // +build linux package file import ( "fmt" "os" "os/user" "path/filepath" "syscall" ) type FileInfo struct { FileType string `json:"fileType"` // file type: file/directory FileMode string `json:"fileMode"` // file mode LinkCount int64 `json:"linkCount"` // link count Owner string `json:"owner"` // owner Group string `json:"group"` // group Size int64 `json:"size"` // size: xx byte ModifiedTime int64 `json:"modifiedTime"` // last modified time:seconds FilePath string `json:"filePath"` // file path FileName string `json:"fileName"` // file name } func GetFileInfo(dir, suffix string) ([]FileInfo, error) { var files []FileInfo err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if path == dir { return nil // 跳过当前目录 } fileType := "file" if info.IsDir() { fileType = "directory" } else if info.Mode()&os.ModeSymlink != 0 { fileType = "symlink" } // check if match suffix if (suffix != "" && filepath.Ext(path) == suffix) || suffix == "" { stat, ok := info.Sys().(*syscall.Stat_t) if !ok { return fmt.Errorf("not a syscall.Stat_t") } userInfo, err := user.LookupId(fmt.Sprint(stat.Uid)) if err != nil { return err } groupInfo, err := user.LookupGroupId(fmt.Sprint(stat.Gid)) if err != nil { return err } fileInfo := FileInfo{ FileType: fileType, FileMode: info.Mode().String(), LinkCount: int64(info.Sys().(*syscall.Stat_t).Nlink), Owner: userInfo.Username, Group: groupInfo.Name, Size: info.Size(), ModifiedTime: info.ModTime().Unix(), FilePath: dir, FileName: info.Name(), } files = append(files, fileInfo) } return nil }) if err != nil { return nil, err } return files, nil }