fs.go 954 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package gin
  2. import (
  3. "net/http"
  4. "os"
  5. )
  6. type (
  7. onlyfilesFS struct {
  8. fs http.FileSystem
  9. }
  10. neuteredReaddirFile struct {
  11. http.File
  12. }
  13. )
  14. // It returns a http.Filesystem that can be used by http.FileServer(). It is used interally
  15. // in router.Static().
  16. // if listDirectory == true, then it works the same as http.Dir() otherwise it returns
  17. // a filesystem that prevents http.FileServer() to list the directory files.
  18. func Dir(root string, listDirectory bool) http.FileSystem {
  19. fs := http.Dir(root)
  20. if listDirectory {
  21. return fs
  22. } else {
  23. return &onlyfilesFS{fs}
  24. }
  25. }
  26. // Conforms to http.Filesystem
  27. func (fs onlyfilesFS) Open(name string) (http.File, error) {
  28. f, err := fs.fs.Open(name)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return neuteredReaddirFile{f}, nil
  33. }
  34. // Overrides the http.File default implementation
  35. func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
  36. // this disables directory listing
  37. return nil, nil
  38. }