另客网go项目公用的代码库

fs.go 1.1KB

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 onlyfilesFS struct {
  10. fs http.FileSystem
  11. }
  12. type neuteredReaddirFile struct {
  13. http.File
  14. }
  15. // Dir returns a http.Filesystem that can be used by http.FileServer(). It is used internally
  16. // in router.Static().
  17. // if listDirectory == true, then it works the same as http.Dir() otherwise it returns
  18. // a filesystem that prevents http.FileServer() to list the directory files.
  19. func Dir(root string, listDirectory bool) http.FileSystem {
  20. fs := http.Dir(root)
  21. if listDirectory {
  22. return fs
  23. }
  24. return &onlyfilesFS{fs}
  25. }
  26. // Open 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. // Readdir 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. }