Go 语言的接口是 Gopher 最喜欢的语法元素之一,其隐式的契约满足和 “当前唯一可用的泛型机制” 的特质让其成为面向组合编程的强大武器,其存在为 Go 建立事物抽象奠定了基础,同时也是建立抽象的主要手段。
Go 语言从诞生至今,最成功的接口定义之一就是 io.Writer 和 io.Reader 接口:
type Writer interface {
Write(p []byte) (n int, err error)
}
type Reader interface {
Read(p []byte) (n int, err error)
}
这两个接口建立了对数据源中的数据操作的良好的抽象,通过该抽象我们可以读或写满足这两个接口的任意数据源:
r := strings.NewReader("hello, go")
r.Read(...)
r := bytes.NewReader([]byte("hello, go"))
r.Read(...)
f := os.Open("foo.txt") // f 满足io.Reader
f.Read(...)
r, err := net.DialTCP("192.168.0.10", nil, raddr *TCPAddr) (*TCPConn, error)
r.Read(...)
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader([]byte("hello, go"))
func main() {
f, err := os.Open("hello.txt.gz")
if err != nil {
log.Fatal(err)
}
zr, err := gzip.NewReader(f)
if err != nil {
log.Fatal(err)
}
if _, err := io.Copy(os.Stdout, zr); err != nil {
log.Fatal(err)
}
if err := zr.Close(); err != nil {
log.Fatal(err)
}
}
... ...
能构架出 io.Reader 和 Writer 这样的抽象,与 Go 最初核心团队的深厚的 Unix 背景是密不可分的,这一抽象可能深受 “在 UNIX 中,一切都是字节流” 这一设计哲学的影响。
Unix 还有一个设计哲学:一切都是文件,即在 Unix 中,任何有 I/O 的设备,无论是文件、socket、驱动等,在打开设备之后都有一个对应的文件描述符,Unix 将对这些设备的操作简化在抽象的文件中了。用户只需要打开文件,将得到的文件描述符传给相应的操作函数,操作系统内核就知道如何根据这个文件描述符得到具体设备信息,内部隐藏了对各种设备进行读写的细节。
并且 Unix 还使用树型的结构将各种抽象的文件 (数据文件、socket、磁盘驱动器、外接设备等) 组织起来,通过文件路径对其进行访问,这样的一个树型结构构成了文件系统。
不过由于历史不知名的某个原因,Go 语言并没有在标准库中内置对文件以及文件系统的抽象!我们知道如今的os.File是一个具体的结构体类型,而不是抽象类型:
// $GOROOT/src/os/types.go
// File represents an open file descriptor.
type File struct {
*file // os specific
}
结构体 os.File 中唯一的字段 file 指针还是一个操作系统相关的类型,我们以 os/file_unix.go 为例,在 unix 中,file 的定义如下:
// file is the real representation of *File.
// The extra level of indirection ensures that no clients of os
// can overwrite this data, which could cause the finalizer
// to close the wrong file descriptor.
type file struct {
pfd poll.FD
name string
dirinfo *dirInfo // nil unless directory being read
nonblock bool // whether we set nonblocking mode
stdoutOrErr bool // whether this is stdout or stderr
appendMode bool // whether file is opened for appending
}
Go 语言之父 Rob Pike 对当初 os.File 没有被定义为 interface 而耿耿于怀:
不过就像 Russ Cox 在上述 issue 中的 comment 那样:“我想我会认为 io.File 应该是接口,但现在这一切都没有意义了”:
但在Go 1.16的 embed 文件功能设计过程中,Go 核心团队以及参与讨论的 Gopher 们认为引入一个对 File System 和 File 的抽象,将会像上面的 io.Reader 和 io.Writer 那样对 Go 代码产生很大益处,同时也会给 embed 功能的实现带去便利!于是 Rob Pike 和 Russ Cox 亲自上阵完成了io/fs 的设计。
io/fs 的加入也不是 “临时起意”,早在很多年前的 godoc 实现时,对一个抽象的文件系统接口的需求就已经被提了出来并给出了实现:
最终这份实现以 godoc 工具的vfs 包的形式一直长期存在着。虽然它的实现有些复杂,抽象程度不够,但却对io/fs 包的设计有着重要的参考价值。
Go 语言对文件系统与文件的抽象以 io/fs 中的 FS 接口类型和 File 类型落地,这两个接口的设计遵循了 Go 语言一贯秉持的“小接口原则”,并符合开闭设计原则 (对扩展开放,对修改关闭)。
// $GOROOT/src/io/fs/fs.go
type FS interface {
// Open opens the named file.
//
// When Open returns an error, it should be of type *PathError
// with the Op field set to "open", the Path field set to name,
// and the Err field describing the problem.
//
// Open should reject attempts to open names that do not satisfy
// ValidPath(name), returning a *PathError with Err set to
// ErrInvalid or ErrNotExist.
Open(name string) (File, error)
}
// A File provides access to a single file.
// The File interface is the minimum implementation required of the file.
// A file may implement additional interfaces, such as
// ReadDirFile, ReaderAt, or Seeker, to provide additional or optimized functionality.
type File interface {
Stat() (FileInfo, error)
Read([]byte) (int, error)
Close() error
}
FS 接口代表虚拟文件系统的最小抽象,它仅包含一个 Open 方法;File 接口则是虚拟文件的最小抽象,仅包含抽象文件所需的三个共同方法 (不能再少了)。我们可以基于这两个接口通过Go 常见的嵌入接口类型的方式进行扩展,就像 io.ReadWriter 是基于 io.Reader 的扩展那样。在这份设计提案中,作者还将这种方式命名为extension interface,即在一个基本接口类型的基础上,新增一到多个新方法以形成一个新接口。比如下面的基于 FS 接口的 extension interface 类型 StatFS:
// A StatFS is a file system with a Stat method.
type StatFS interface {
FS
// Stat returns a FileInfo describing the file.
// If there is an error, it should be of type *PathError.
Stat(name string) (FileInfo, error)
}
对于 File 这个基本接口类型,fs 包仅给出一个 extension interface:ReadDirFile,即在 File 接口的基础上增加了一个 ReadDir 方法形成的,这种用扩展方法名 + 基础接口名来命名一个新接口类型的方式也是 Go 的惯用法。
对于 FS 接口,fs 包给出了一些扩展 FS 的常见 “新扩展接口” 的样例:
以 fs 包的 ReadDirFS 接口为例:
// $GOROOT/src/io/fs/readdir.go
type ReadDirFS interface {
FS
// ReadDir reads the named directory
// and returns a list of directory entries sorted by filename.
ReadDir(name string) ([]DirEntry, error)
}
// ReadDir reads the named directory
// and returns a list of directory entries sorted by filename.
//
// If fs implements ReadDirFS, ReadDir calls fs.ReadDir.
// Otherwise ReadDir calls fs.Open and uses ReadDir and Close
// on the returned file.
func ReadDir(fsys FS, name string) ([]DirEntry, error) {
if fsys, ok := fsys.(ReadDirFS); ok {
return fsys.ReadDir(name)
}
file, err := fsys.Open(name)
if err != nil {
return nil, err
}
defer file.Close()
dir, ok := file.(ReadDirFile)
if !ok {
return nil, &PathError{Op: "readdir", Path: name, Err: errors.New("not implemented")}
}
list, err := dir.ReadDir(-1)
sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
return list, err
}
我们看到伴随着 ReadDirFS,标准库还提供了一个 helper 函数:ReadDir。该函数的第一个参数为 FS 接口类型的变量,在其内部实现中,ReadDir 先通过类型断言判断传入的 fsys 是否实现了 ReadDirFS,如果实现了,就直接调用其 ReadDir 方法;如果没有实现则给出了常规实现。其他几个 FS 的 extension interface 也都有自己的 helper function,这也算是 Go 的一个惯例。如果你要实现你自己的 FS 的扩展,不要忘了这个惯例:给出伴随你的扩展接口的 helper function。
标准库中一些涉及虚拟文件系统的包在 Go 1.16 版本中做了对 io/fs 的适配,比如:os、net/http、html/template、text/template、archive/zip 等。
以 http.FileServer 为例,Go 1.16 版本之前建立一个静态文件 Server 一般这么来写:
// github.com/bigwhite/experiments/blob/master/iofs/fileserver_classic.go
package main
import "net/http"
func main() {
http.ListenAndServe(":8080", http.FileServer(http.Dir(".")))
}
Go 1.16 http 包对 fs 的 FS 和 File 接口做了适配后,我们可以这样写:
// github.com/bigwhite/experiments/blob/master/iofs/fileserver_iofs.go
package main
import (
"net/http"
"os"
)
func main() {
http.ListenAndServe(":8080", http.FileServer(http.FS(os.DirFS("./"))))
}
os 包新增的 DirFS 函数返回一个 fs.FS 的实现:一个以传入 dir 为根的文件树构成的 File System。
我们可以参考 DirFS 实现一个 goFilesFS,该 FS 的实现仅返回以.go 为后缀的文件:
// github.com/bigwhite/experiments/blob/master/iofs/gofilefs/gofilefs.go
package gfs
import (
"io/fs"
"os"
"strings"
)
func GoFilesFS(dir string) fs.FS {
return goFilesFS(dir)
}
type goFile struct {
*os.File
}
func Open(name string) (*goFile, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
return &goFile{f}, nil
}
func (f goFile) ReadDir(count int) ([]fs.DirEntry, error) {
entries, err := f.File.ReadDir(count)
if err != nil {
return nil, err
}
var newEntries []fs.DirEntry
for _, entry := range entries {
if !entry.IsDir() {
ss := strings.Split(entry.Name(), ".")
if ss[len(ss)-1] != "go" {
continue
}
}
newEntries = append(newEntries, entry)
}
return newEntries, nil
}
type goFilesFS string
func (dir goFilesFS) Open(name string) (fs.File, error) {
f, err := Open(string(dir) + "/" + name)
if err != nil {
return nil, err // nil fs.File
}
return f, nil
}
上述 GoFilesFS 的实现中:
有了 GoFilesFS 的实现后,我们就可以将其传给 http.FileServer 了:
// github.com/bigwhite/experiments/blob/master/iofs/fileserver_gofilefs.go
package main
import (
"net/http"
gfs "github.com/bigwhite/testiofs/gofilefs"
)
func main() {
http.ListenAndServe(":8080", http.FileServer(http.FS(gfs.GoFilesFS("./"))))
}
通过浏览器打开 localhost:8080 页面,我们就能看到仅由 go 源文件组成的文件树!
抽象的接口意味着降低耦合,意味着代码可测试性的提升。Go 1.16 增加了对文件系统和文件的抽象之后,我们以后再面对文件相关代码时,我们便可以利用 io/fs 提高这类代码的可测试性。
我们有这样的一个函数:
func FindGoFiles(dir string) ([]string, error)
该函数查找出 dir 下所有 go 源文件的路径并放在一个 [] string 中返回。我们可以很轻松的给出下面的第一版实现:
// github.com/bigwhite/experiments/blob/master/iofs/gowalk/demo1/gowalk.go
package demo
import (
"os"
"path/filepath"
"strings"
)
func FindGoFiles(dir string) ([]string, error) {
var goFiles []string
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
ss := strings.Split(path, ".")
if ss[len(ss)-1] != "go" {
return nil
}
goFiles = append(goFiles, path)
return nil
})
if err != nil {
return nil, err
}
return goFiles, nil
}
这一版的实现直接使用了 filepath 的 Walk 函数,它与 os 包是紧绑定的,即要想测试这个函数,我们需要在磁盘上真实的构造出一个文件树,就像下面这样:
$tree testdata
testdata
└── foo
├── 1
│ └── 1.txt
├── 1.go
├── 2
│ ├── 2.go
│ └── 2.txt
└── bar
├── 3
│ └── 3.go
└── 4.go
按照 go 惯例,我们将测试依赖的外部数据文件放在 testdata 下面。下面是针对上面函数的测试文件:
// github.com/bigwhite/experiments/blob/master/iofs/gowalk/demo1/gowalk_test.go
package demo
import (
"testing"
)
func TestFindGoFiles(t *testing.T) {
m := map[string]bool{
"testdata/foo/1.go": true,
"testdata/foo/2/2.go": true,
"testdata/foo/bar/3/3.go": true,
"testdata/foo/bar/4.go": true,
}
files, err := FindGoFiles("testdata/foo")
if err != nil {
t.Errorf("want nil, actual %s", err)
}
if len(files) != 4 {
t.Errorf("want 4, actual %d", len(files))
}
for _, f := range files {
_, ok := m[f]
if !ok {
t.Errorf("want [%s], actual not found", f)
}
}
}
FindGoFiles 函数的第一版设计显然可测性较差,需要对依赖特定布局的磁盘上的文件,虽然 testdata 也是作为源码提交到代码仓库中的。
有了 io/fs 包后,我们用 FS 接口来提升一下 FindGoFiles 函数的可测性,我们重新设计一下该函数:
// github.com/bigwhite/experiments/blob/master/iofs/gowalk/demo2/gowalk.go
package demo
import (
"io/fs"
"strings"
)
func FindGoFiles(dir string, fsys fs.FS) ([]string, error) {
var newEntries []string
err := fs.WalkDir(fsys, dir, func(path string, entry fs.DirEntry, err error) error {
if entry == nil {
return nil
}
if !entry.IsDir() {
ss := strings.Split(entry.Name(), ".")
if ss[len(ss)-1] != "go" {
return nil
}
newEntries = append(newEntries, path)
}
return nil
})
if err != nil {
return nil, err
}
return newEntries, nil
}
这次我们给 FindGoFiles 增加了一个 fs.FS 类型的参数 fsys,这是解除掉该函数与具体 FS 实现的关键。当然 demo1 的测试方法同样适用于该版 FindGoFiles 函数:
// github.com/bigwhite/experiments/blob/master/iofs/gowalk/demo2/gowalk_test.go
package demo
import (
"os"
"testing"
)
func TestFindGoFiles(t *testing.T) {
m := map[string]bool{
"testdata/foo/1.go": true,
"testdata/foo/2/2.go": true,
"testdata/foo/bar/3/3.go": true,
"testdata/foo/bar/4.go": true,
}
files, err := FindGoFiles("testdata/foo", os.DirFS("."))
if err != nil {
t.Errorf("want nil, actual %s", err)
}
if len(files) != 4 {
t.Errorf("want 4, actual %d", len(files))
}
for _, f := range files {
_, ok := m[f]
if !ok {
t.Errorf("want [%s], actual not found", f)
}
}
}
但这不是我们想要的,既然我们使用了 io/fs.FS 接口,那么一切实现了 fs.FS 接口的实体均可被用来构造针对 FindGoFiles 的测试。但自己写一个实现了 fs.FS 接口以及 fs.File 相关接口还是比较麻烦的,Go 标准库已经想到了这点,为我们提供了 testing/fstest 包,我们可以直接利用 fstest 包中实现的基于 memory 的 FS 来对 FindGoFiles 进行测试:
// github.com/bigwhite/experiments/blob/master/iofs/gowalk/demo3/gowalk_test.go
package demo
import (
"testing"
"testing/fstest"
)
/*
$tree testdata
testdata
└── foo
├── 1
│ └── 1.txt
├── 1.go
├── 2
│ ├── 2.go
│ └── 2.txt
└── bar
├── 3
│ └── 3.go
└── 4.go
5 directories, 6 files
*/
func TestFindGoFiles(t *testing.T) {
m := map[string]bool{
"testdata/foo/1.go": true,
"testdata/foo/2/2.go": true,
"testdata/foo/bar/3/3.go": true,
"testdata/foo/bar/4.go": true,
}
mfs := fstest.MapFS{
"testdata/foo/1.go": {Data: []byte("package foo\n")},
"testdata/foo/1/1.txt": {Data: []byte("1111\n")},
"testdata/foo/2/2.txt": {Data: []byte("2222\n")},
"testdata/foo/2/2.go": {Data: []byte("package bar\n")},
"testdata/foo/bar/3/3.go": {Data: []byte("package zoo\n")},
"testdata/foo/bar/4.go": {Data: []byte("package zoo1\n")},
}
files, err := FindGoFiles("testdata/foo", mfs)
if err != nil {
t.Errorf("want nil, actual %s", err)
}
if len(files) != 4 {
t.Errorf("want 4, actual %d", len(files))
}
for _, f := range files {
_, ok := m[f]
if !ok {
t.Errorf("want [%s], actual not found", f)
}
}
}
由于 FindGoFiles 接受了 fs.FS 类型变量作为参数,使其可测性显著提高,我们可以通过代码来构造测试场景,而无需在真实物理磁盘上构造复杂多变的测试场景。
io/fs 的加入让我们易于面向接口编程,而不是面向 os.File 这个具体实现。io/fs 的加入丝毫没有违和感,就好像这个包以及其中的抽象在 Go 1.0 版本发布时就存在的一样。这也是 Go interface 隐式依赖的特质带来的好处,让人感觉十分得劲儿!
本文中涉及的代码可以在这里下载。https://github.com/bigwhite/experiments/tree/master/iofs
Go 技术专栏 “改善 Go 语⾔编程质量的 50 个有效实践” 正在慕课网火热热销中!本专栏主要满足广大 gopher 关于 Go 语言进阶的需求,围绕如何写出地道且高质量 Go 代码给出 50 条有效实践建议,上线后收到一致好评!欢迎大家订阅!
我的网课 “Kubernetes 实战:高可用集群搭建、配置、运维与应用” 在慕课网热卖中,欢迎小伙伴们订阅学习!
Gopher Daily(Gopher 每日新闻) 归档仓库 - https://github.com/bigwhite/gopherdaily
我的联系方式: