utils.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package filesystem
  2. import (
  3. "fmt"
  4. "html"
  5. "net/http"
  6. "os"
  7. "path"
  8. "sort"
  9. "strings"
  10. "github.com/gofiber/fiber/v2"
  11. "github.com/gofiber/fiber/v2/utils"
  12. )
  13. func getFileExtension(p string) string {
  14. n := strings.LastIndexByte(p, '.')
  15. if n < 0 {
  16. return ""
  17. }
  18. return p[n:]
  19. }
  20. func dirList(c *fiber.Ctx, f http.File) error {
  21. fileinfos, err := f.Readdir(-1)
  22. if err != nil {
  23. return fmt.Errorf("failed to read dir: %w", err)
  24. }
  25. fm := make(map[string]os.FileInfo, len(fileinfos))
  26. filenames := make([]string, 0, len(fileinfos))
  27. for _, fi := range fileinfos {
  28. name := fi.Name()
  29. fm[name] = fi
  30. filenames = append(filenames, name)
  31. }
  32. basePathEscaped := html.EscapeString(c.Path())
  33. _, _ = fmt.Fprintf(c, "<html><head><title>%s</title><style>.dir { font-weight: bold }</style></head><body>", basePathEscaped)
  34. _, _ = fmt.Fprintf(c, "<h1>%s</h1>", basePathEscaped)
  35. _, _ = fmt.Fprint(c, "<ul>")
  36. if len(basePathEscaped) > 1 {
  37. parentPathEscaped := html.EscapeString(utils.TrimRight(c.Path(), '/') + "/..")
  38. _, _ = fmt.Fprintf(c, `<li><a href="%s" class="dir">..</a></li>`, parentPathEscaped)
  39. }
  40. sort.Strings(filenames)
  41. for _, name := range filenames {
  42. pathEscaped := html.EscapeString(path.Join(c.Path() + "/" + name))
  43. fi := fm[name]
  44. auxStr := "dir"
  45. className := "dir"
  46. if !fi.IsDir() {
  47. auxStr = fmt.Sprintf("file, %d bytes", fi.Size())
  48. className = "file"
  49. }
  50. _, _ = fmt.Fprintf(c, `<li><a href="%s" class="%s">%s</a>, %s, last modified %s</li>`,
  51. pathEscaped, className, html.EscapeString(name), auxStr, fi.ModTime())
  52. }
  53. _, _ = fmt.Fprint(c, "</ul></body></html>")
  54. c.Type("html")
  55. return nil
  56. }