在Golang中,可以将文件系统嵌入到二进制文件中,并与库一起使用。

huangapple go评论70阅读模式
英文:

Golang - embedding filesystem in binary; using with libraries

问题

我正在使用go.rice将嵌入式文件系统存储在Go二进制文件中。这对于推送到生产环境(即单个二进制分发)非常完美,并且将所有的“文件”访问都保留在内存中。

我遇到的问题是一些第三方库设计成直接通过传入文件名字符串来加载外部文件(而不是像通用的Reader接口那样,允许我抽象文件加载)。

是否有一种方法可以创建一个与Go标准库os/io工具兼容的内存文件系统,从而绕过将资源存储在二进制文件之外的需求?

我可以将字节转储到临时文件中,将其传递给库,然后删除...但这看起来很混乱。如果可能的话,我更希望保持在内存中进行访问。

不一定非要使用go.rice...还有其他嵌入机制可以实现清晰的/单个文件分发吗?

英文:

I'm using go.rice to store an embedded filesystem in the Go binary. This works perfectly for pushing to production (i.e. single binary distribution), and keeps all 'file' access in memory.

The issue I'm running into is third-party libs that are designed to load external files from the filesystem directly by passing in a file name string (rather than, say, a generic Reader interface that would have allowed me to abstract file loading)

Is there some way to create an in-memory filesystem that works with Go's standard library os/io tools and therefore bypass the need to store assets outside of the binary?

I could dump the bytes to a tmp file, pass that to the libs, and then delete... but that seems messy. Would prefer to keep access in memory, if possible.

Doesn't have to be go.rice... any other embedding mechanisms to keep this clear/single file distribution?

答案1

得分: 1

抱歉,这是不可能的。os包是对操作系统API的薄包装。你可以这样做:

  1. 使用go.rice在你的二进制文件中创建一个嵌入式文件系统。
  2. 在运行时:将嵌入的文件复制到临时位置(你可以使用os.TempDir()获取一个适合创建临时目录的位置)。
  3. 使用临时路径将文件名传递给第三方代码。
  4. 在程序退出时,清理临时目录。

或者,你可以请求第三方代码的开发者添加一个额外的API,接受io.Reader而不是文件名。

英文:

I'm sorry, that is not possible. The os package is a thin wrapper atop the platforms operating system API. What you could do is this:

  1. Use go.rice to create an embedded file system in your binary.
  2. At runtime: copy the embedded file to a temporary location (you can use os.TempDir() to get a suitable place to make your temporary directory in)
  3. Use the temporary path to pass file names to third-party code.
  4. On program exit, clean up the temporary directory.

Alternatively, you could request the developers of the third-party code to include an extra API that accepts an io.Reader instead of a file name.

huangapple
  • 本文由 发表于 2014年8月3日 23:26:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/25106182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定