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