fs.go 944 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. // Dir 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. }
  23. return &onlyfilesFS{fs}
  24. }
  25. // Conforms to http.Filesystem
  26. func (fs onlyfilesFS) Open(name string) (http.File, error) {
  27. f, err := fs.fs.Open(name)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return neuteredReaddirFile{f}, nil
  32. }
  33. // Overrides the http.File default implementation
  34. func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
  35. // this disables directory listing
  36. return nil, nil
  37. }