golang开发的时候,可以把静态文件打包到二进制文件中!它的实现完全是golang易用的interface实现的!golang中大量的使用了interface,很多方法都可以重写或者说继承实现!当然也包括文件系统!

golang 默认的文件系统是读取磁盘中的文件,读取后进行模板的解析,从而展现页面,这个文件系统也是接口实现的,所以我们重写文件系统的接口,是文件读取不再是系统磁盘,而是内存系统,把系统文件编译到我们程序之中使之成为内存文件,这样我门就打包文件系统到二进制文件中啦!

看看具体怎么实现

Go
1
http.Handle("/",http.FileServer(http.Dir("/")))

上边这是golang自带的是静态文件服务的代码,http.FileServer 接收的就是 FileSystem

Go
1
2
3
func FileServer(root FileSystem) Handler {
return &fileHandler{root}
}

上边是golang 系统代码,fileServer接收了FileSystem,所以我们就实现这个FileSystem,接着我们看看这个代码是啥!继续追踪

Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type FileSystem interface {
Open(name string) (File, error)
}
 
// A File is returned by a FileSystem's Open method and can be
// served by the FileServer implementation.
//
// The methods should behave the same as those on an *os.File.
type File interface {
io.Closer
io.Reader
io.Seeker
Readdir(count int) ([]os.FileInfo, error)
Stat() (os.FileInfo, error)
}

上边也是golang 系统代码,看到了码,FileSystem是个接口,并且有个方法Open,同时返回了一个File,而且File也是一个接口!这样,我们就好办啦,我们只要按这两个的接口定义,实现接口就好啦!我们重新定义这个FileSystem,使系统文件放到系统内存变量中,我们读取的时候,在变量中读取!

这里推荐一个类库,已经完全实现上边的接口,并且做了压缩

github.com/rakyll/statik

下篇,我们接着介绍这个类库的实现和我们模板中怎么替换系统文件系统而使用我们放到内存中的文件!