如何在 go 中模拟/抽象文件系统? [英] How to mock/abstract filesystem in go?

查看:24
本文介绍了如何在 go 中模拟/抽象文件系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将我的 Go 应用程序发出的每次写入/读取记录到底层操作系统,并且(如果可能的话)将 FS 完全替换为仅驻留在内存中的 FS.

I would like to be able to log every write/read that my go app issues to the underlying OS, and also (if it's possible) completely replace FS with one that resides only in memory.

有可能吗?如何?也许有现成的解决方案?

Is it possible? How? Maybe there is a ready-to-Go solution?

推荐答案

这直接来自 Andrew Gerrand 的 10你(可能)不知道的关于 Go 的事情:

This is straight from Andrew Gerrand's 10 things you (probably) don't know about Go:

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 表示默认文件系统).

For this to work, you will need to write your code to take a fileSystem argument (maybe embed it in some other type, or let nil denote the default filesystem).

这篇关于如何在 go 中模拟/抽象文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆