本文介绍了将[]字节转换为“虚拟"字节的简单方法Golang中的文件对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有Go库可以创建整个文件系统,例如 VFS .但是我只想将字节数组放入可以满足 File 接口的对象中

I know there are Go libraries that create entire filesystems like VFS. But I only want to make a byte array into something that can fulfil the File interface.

推荐答案

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

There is no ready solution for this in the standard library, but it's not that hard to do it yourself.

我们需要的是> http.File 界面:

What we need is this http.File interface:

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()甚至都不会被调用.

Please note that we can utilize bytes.Reader to do the heavy task, as that alone implements io.Reader and io.Seeker. io.Closer can be a noop, and Readdir() may return nil, nil as we're mocking a file not a directory, its Readdir() won't even be called.

最困难"的部分是模拟 Stat()以返回实现 os.FileInfo .

The "hardest" part is to mock Stat() to return a value that implements os.FileInfo.

这是一个简单的模拟的 FileInfo :

Here's a simple mocked 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 all
func (mif myFileInfo) ModTime() time.Time { return time.Time{} } // Return anything
func (mif myFileInfo) IsDir() bool        { return false }
func (mif myFileInfo) Sys() interface{}   { return nil }

有了这些,我们就可以创建模拟的 http.File :

And with that we have everything to create our mocked http.File:

type MyFile struct {
    *bytes.Reader
    mif myFileInfo
}

func (mf *MyFile) Close() error { return nil } // Noop, nothing to do

func (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
}

使用它的示例(在进入游乐场中尝试):

Example using it (try it on the 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中的文件对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:26