有人可以解释一下“Readdir”和“Open”包装方法吗

我是高朗的新手。有人可以解释一下“Readdir”和“Open”包装器方法是如何工作的吗?


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


更具体地说,在“Readdir”方法中,该语句files, err := f.File.Readdir(n)具有 n 个 int 值,但它是从哪里传递的以及它是如何工作的。程序中的任何地方都没有调用“Readdir”方法。


同样在“打开”包装器中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 thehttp.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

    }




DIEA
浏览 75回答 1
1回答

萧十郎

dotFileHidingFileSystem 类型包装了一个http.FileSystem,它本身就是一个 http.FileSystem。dotFileHidingFile 类型包装了一个http.File,它本身就是一个 http.File。因为这两个结构类型嵌入了包装值,包装值上的所有方法都被提升为包装器类型上的方法,除非包装器类型本身实现了该方法。如果您不熟悉嵌入概念,请阅读有关嵌入的 Effective Go 部分。net/http文件服务器调用http.FileSystem和 http.File 接口上的方法。文件服务器调用文件系统的Open 方法打开一个文件。该方法的 dotFileHidingFileSystem 实现调用包装的文件系统以打开文件并返回围绕该文件的 dotFileHidingFile 包装器。如果文件是目录,文件服务器调用文件Readdir方法来获取目录中文件的列表。文件服务器指定 的值n。Readdir 方法的 dotFileHidingFile 实现通过包装文件 Readdir 方法调用并从结果中过滤点文件。有关 Readdir 参数的文档,请参阅ReadDirFile文档n。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go