@@ -9,37 +9,43 @@ import (
99 "os"
1010)
1111
12- type onlyFilesFS struct {
13- fs http.FileSystem
12+ // OnlyFilesFS implements an http.FileSystem without `Readdir` functionality.
13+ type OnlyFilesFS struct {
14+ FileSystem http.FileSystem
1415}
1516
16- type neuteredReaddirFile struct {
17+ // Open passes `Open` to the upstream implementation without `Readdir` functionality.
18+ func (o OnlyFilesFS ) Open (name string ) (http.File , error ) {
19+ f , err := o .FileSystem .Open (name )
20+
21+ if err != nil {
22+ return nil , err
23+ }
24+
25+ return neutralizedReaddirFile {f }, nil
26+ }
27+
28+ // neutralizedReaddirFile wraps http.File with a specific implementation of `Readdir`.
29+ type neutralizedReaddirFile struct {
1730 http.File
1831}
1932
20- // Dir returns a http.FileSystem that can be used by http.FileServer(). It is used internally
21- // in router.Static().
22- // if listDirectory == true, then it works the same as http.Dir() otherwise it returns
23- // a filesystem that prevents http.FileServer() to list the directory files.
33+ // Readdir overrides the http.File default implementation and always returns nil.
34+ func (n neutralizedReaddirFile ) Readdir (_ int ) ([]os.FileInfo , error ) {
35+ // this disables directory listing
36+ return nil , nil
37+ }
38+
39+ // Dir returns an http.FileSystem that can be used by http.FileServer().
40+ // It is used internally in router.Static().
41+ // if listDirectory == true, then it works the same as http.Dir(),
42+ // otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.
2443func Dir (root string , listDirectory bool ) http.FileSystem {
2544 fs := http .Dir (root )
45+
2646 if listDirectory {
2747 return fs
2848 }
29- return & onlyFilesFS {fs }
30- }
31-
32- // Open conforms to http.Filesystem.
33- func (fs onlyFilesFS ) Open (name string ) (http.File , error ) {
34- f , err := fs .fs .Open (name )
35- if err != nil {
36- return nil , err
37- }
38- return neuteredReaddirFile {f }, nil
39- }
4049
41- // Readdir overrides the http.File default implementation.
42- func (f neuteredReaddirFile ) Readdir (_ int ) ([]os.FileInfo , error ) {
43- // this disables directory listing
44- return nil , nil
50+ return & OnlyFilesFS {FileSystem : fs }
4551}
0 commit comments