标准库中尚无现成的解决方案,但您自己做起来并不难。
我们需要的是此
http.File接口:
type File interface { io.Closer io.Reader io.Seeker Readdir(count int) ([]os.FileInfo, error) Stat() (os.FileInfo, error)}请注意,我们可以利用它
bytes.Reader来完成繁重的任务,因为这是单独实现
io.Reader和的
io.Seeker。
io.Closer可以是noop,并且
Readdir()可能
nil,nil在模拟文件而不是目录时返回,
Readdir()甚至不会被调用。
“最难”的部分是模拟
Stat()返回实现的值
os.FileInfo。
这是一个简单的嘲笑
FileInfo:
type myFileInfo struct { name string data []byte}func (mif myFileInfo) Name() string { return mif.name }func (mif myFileInfo) Size() int64 { return int64(len(mif.data)) }func (mif myFileInfo) Mode() os.FileMode { return 0444 } // Read for allfunc (mif myFileInfo) ModTime() time.Time { return time.Time{} } // Return anythingfunc (mif myFileInfo) IsDir() bool { return false }func (mif myFileInfo) Sys() interface{} { return nil }这样,我们就拥有了创建模拟对象的一切
http.File:
type MyFile struct { *bytes.Reader mif myFileInfo}func (mf *MyFile) Close() error { return nil } // Noop, nothing to dofunc (mf *MyFile) Readdir(count int) ([]os.FileInfo, error) { return nil, nil // We are not a directory but a single file}func (mf *MyFile) Stat() (os.FileInfo, error) { return mf.mif, nil}使用它的示例(在Go Playground上尝试):
data:= []byte{0, 1, 2, 3}mf := &MyFile{ Reader: bytes.NewReader(data), mif: myFileInfo{ name: "somename.txt", data: data, },}var f http.File = mf_ = f

![在golang中将[]字节转换成“虚拟”文件对象的简单方法? 在golang中将[]字节转换成“虚拟”文件对象的简单方法?](http://www.mshxw.com/aiimages/31/378888.png)
