Source file
src/net/http/example_filesystem_test.go
1
2
3
4
5 package http_test
6
7 import (
8 "io"
9 "io/fs"
10 "log"
11 "net/http"
12 "strings"
13 )
14
15
16
17
18 func containsDotFile(name string) bool {
19 parts := strings.Split(name, "/")
20 for _, part := range parts {
21 if strings.HasPrefix(part, ".") {
22 return true
23 }
24 }
25 return false
26 }
27
28
29
30
31 type dotFileHidingFile struct {
32 http.File
33 }
34
35
36
37 func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) {
38 files, err := f.File.Readdir(n)
39 for _, file := range files {
40 if !strings.HasPrefix(file.Name(), ".") {
41 fis = append(fis, file)
42 }
43 }
44 if err == nil && n > 0 && len(fis) == 0 {
45 err = io.EOF
46 }
47 return
48 }
49
50
51
52 type dotFileHidingFileSystem struct {
53 http.FileSystem
54 }
55
56
57
58
59 func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) {
60 if containsDotFile(name) {
61 return nil, fs.ErrPermission
62 }
63
64 file, err := fsys.FileSystem.Open(name)
65 if err != nil {
66 return nil, err
67 }
68 return dotFileHidingFile{file}, err
69 }
70
71 func ExampleFileServer_dotFileHiding() {
72 fsys := dotFileHidingFileSystem{http.Dir(".")}
73 http.Handle("/", http.FileServer(fsys))
74 log.Fatal(http.ListenAndServe(":8080", nil))
75 }
76
View as plain text