path.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package inout
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. )
  8. type Folder struct {
  9. Display string
  10. Nume string
  11. Fisiere []File
  12. Subfoldere []Folder
  13. }
  14. type File struct {
  15. Nume string
  16. Path string
  17. }
  18. func SafeDir(path string) error {
  19. path = filepath.Clean(path)
  20. if strings.HasPrefix(path, "..") || filepath.IsAbs(path) {
  21. return fmt.Errorf("Invalid Path")
  22. }
  23. return nil
  24. }
  25. func GetFolderStructure(path string, f *Folder) error {
  26. entries, err := os.ReadDir(path)
  27. if err != nil {
  28. return err
  29. }
  30. if filepath.Clean(path) != "notes_folder" {
  31. f.Nume = strings.TrimPrefix(path, "notes_folder/")
  32. } else {
  33. f.Nume = "notes_folder"
  34. }
  35. f.Display = filepath.Base(path)
  36. for _, entry := range entries {
  37. if entry.IsDir() {
  38. sub := Folder{}
  39. err = GetFolderStructure(filepath.Join(path, entry.Name()), &sub)
  40. if err != nil {
  41. return err
  42. }
  43. f.Subfoldere = append(f.Subfoldere, sub)
  44. } else {
  45. fisier := File{
  46. Nume: entry.Name(),
  47. Path: filepath.Join(path, entry.Name()),
  48. }
  49. f.Fisiere = append(f.Fisiere, fisier)
  50. }
  51. }
  52. return nil
  53. }