我希望能记录我的Go应用程序发出的所有写入/读取底层操作系统的日志,并且(如果可能的话)完全替换文件系统为仅驻留在内存中的文件系统。
这是否可行?怎么做?也许有现成的解决方案吗?
我希望能记录我的Go应用程序发出的所有写入/读取底层操作系统的日志,并且(如果可能的话)完全替换文件系统为仅驻留在内存中的文件系统。
这是否可行?怎么做?也许有现成的解决方案吗?
这是直接从Andrew Gerrand的《关于Go语言你 (可能) 不知道的10件事》中摘录的:
var fs fileSystem = osFS{}
type fileSystem interface {
Open(name string) (file, error)
Stat(name string) (os.FileInfo, error)
}
type file interface {
io.Closer
io.Reader
io.ReaderAt
io.Seeker
Stat() (os.FileInfo, error)
}
// osFS implements fileSystem using the local disk.
type osFS struct{}
func (osFS) Open(name string) (file, error) { return os.Open(name) }
func (osFS) Stat(name string) (os.FileInfo, error) { return os.Stat(name) }
为了让这个工作,您需要编写您的代码以接受一个fileSystem
参数(可能将其嵌入其他类型中,或者让nil
表示默认文件系统)。如果你正在寻找解决测试期间模拟文件系统的问题,可以查看 @spf13 的 Afero 库,https://github.com/spf13/afero。它可以完成已被接受答案所能做的所有事情,但是文档和示例更好。
io/fs
的即插即用替代品。https://github.com/spf13/afero/issues/325 - G. Kashtanov afero.Fs
转换为 afero.IOFS
”。链接:https://github.com/spf13/afero/issues/325#issuecomment-1115075828 - Benjamin Rtesting/fstest
包:package main
import "testing/fstest"
func main() {
fs := fstest.MapFS{
"hello.txt": {
Data: []byte("hello, world"),
},
}
data, err := fs.ReadFile("hello.txt")
if err != nil {
panic(err)
}
println(string(data) == "hello, world")
}
fstest.MapFS{"tmp": {Mode: fs.ModeDir}}
。 - G. Kashtanovfstest.MapFS{"/do/not/use/absolute/paths/no.txt": {}}
以下写法是正确的:
fstest.MapFS{"relative/path/with/no/leading/slash/ok.txt": {}}
我不小心添加了一个绝对路径,这些条目在测试中被省略了。奇怪的是,一个空的“name”目录被添加了进去。 - Bouncing Bit只是因为这个问题在谷歌搜索时排名很高:
我不知道如何记录读写日志,但对于仅驻留在内存中的文件系统,我发现了blang/vfs。我没有在生产中使用过,并且它说它是α版,接口可能会更改。自行承担风险。
我想你可以实现它来记录读写操作。
os.Open
呢?赋值fs
变量会“悄悄地”影响它们吗? - canni