fs.go 1.1 KB

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