亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有人可以解釋一下“Readdir”和“Open”包裝方法嗎

有人可以解釋一下“Readdir”和“Open”包裝方法嗎

Go
DIEA 2022-12-19 18:22:46
我是高朗的新手。有人可以解釋一下“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 mainimport (    "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    }
查看完整描述

1 回答

?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

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。



查看完整回答
反對 回復 2022-12-19
  • 1 回答
  • 0 關注
  • 90 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號