栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在golang中将[]字节转换成“虚拟”文件对象的简单方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在golang中将[]字节转换成“虚拟”文件对象的简单方法?

标准库中尚无现成的解决方案,但您自己做起来并不难。

我们需要的是此

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/378888.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号