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