有人可以解释一下"Readdir"和"Open"包装器方法



我是高朗的新手。有没有人能解释一下,如何"阅读"?和";Open"包装器方法是否有效?

这个例子来自Golang文档。https://pkg.go.dev/net/http example-FileServer-DotFileHiding

更具体地说,在"阅读目录"中。方法,语句files, err := f.File.Readdir(n)有n个int值,但从它传递的位置和它是如何工作的。"Readdir"方法不能在程序的任何地方调用。

类似于"Open"包装器file, err := fsys.FileSystem.Open(name)

package main
import (
"io/fs"
"log"
"net/http"
"strings"
)
// containsDotFile reports whether name contains a path element starting with a period.
// The name is assumed to be a delimited by forward slashes, as guaranteed
// by the http.FileSystem interface.
func containsDotFile(name string) bool {
parts := strings.Split(name, "/")
for _, part := range parts {
if strings.HasPrefix(part, ".") {
return true
}
}
return false
}
// dotFileHidingFile is the http.File use in dotFileHidingFileSystem.
// It is used to wrap the Readdir method of http.File so that we can
// remove files and directories that start with a period from its output.
type dotFileHidingFile struct {
http.File
}
f
// Readdir is a wrapper around the Readdir method of the embedded File
// that filters out all files that start with a period in their name.
func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) {
files, err := f.File.Readdir(n)
for _, file := range files { // Filters out the dot files
if !strings.HasPrefix(file.Name(), ".") {
fis = append(fis, file)
}
}
return
}
// dotFileHidingFileSystem is an http.FileSystem that hides
// hidden "dot files" from being served.
type dotFileHidingFileSystem struct {
http.FileSystem
}
// Open is a wrapper around the Open method of the embedded FileSystem
// that serves a 403 permission error when name has a file or directory
// with whose name starts with a period in its path.
func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) {
if containsDotFile(name) { // If dot file, return 403 response
return nil, fs.ErrPermission
}
file, err := fsys.FileSystem.Open(name)
if err != nil {
return nil, err
}
return dotFileHidingFile{file}, err
}
func main() {
fsys := dotFileHidingFileSystem{http.Dir(".")}
http.Handle("/", http.FileServer(fsys))
log.Fatal(http.ListenAndServe(":8080", nil))
}

dotFileHidingFileSystem类型包装一个http。文件系统,它本身就是一个http.FileSystem。

dotFileHidingFile类型包装一个http。

因为这两个结构类型嵌入了包装的值,所以包装值上的所有方法都被提升为包装器类型上的方法,除非包装器类型本身实现了该方法。如果您不熟悉嵌入的概念,请阅读Effective Go关于嵌入的部分。

. net/http文件服务器调用http。文件系统和http。文件接口。

文件服务器调用文件系统Open方法打开文件。该方法的dotFileHidingFileSystem实现通过调用包装的文件系统打开文件,并返回该文件周围的dotFileHidingFile包装器。

如果文件是一个目录,文件服务器调用file Readdir方法来获取目录中文件的列表。文件服务器设置为"n"。Readdir方法的dotFileHidingFile实现通过包装文件Readdir方法调用,并从结果中过滤点文件。

请参阅ReadDirFile文档,了解关于Readdir的n参数的文档。

最新更新