how to generate an embed.FS?

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

how to generate an embed.FS?

问题

我有一个embed.FS,像这样:

//go:embed static
var embedStatic embed.FS

我想在启动时通过minifier传递文件。我希望能够创建一个内存中的fs.FS,其中包含与embedStatic上可用的相同文件,但其内容经过了缩小。

我知道有外部库(如Afero和MemFS),但我通常会尽量避免添加依赖项。

我也知道我可以通过创建一个新的接口并自己实现我关心的所有方法(fs.FSOpenReadDir等)来实现这一点,但似乎embed.FS已经完成了我想做的一切,除了文件的构建。

我的问题是:在重用embed.FS的同时是否有办法做到这一点?我能够动态创建一个embed.FS吗?

我在这里看到embed.FS有一个files *[]file,但显然是私有的。我想知道是否有一种方法可以创建一个新类型,并告诉Go“假装这是正确创建的,并将其视为embed.FS”。

英文:

I have a embed.FS, like:

//go:embed static
var embedStatic embed.FS

and I want to (at startup time) pass the files through a minifier. I want to be able to create an in-memory fs.FS with the same files available on embedStatic, but with their content minified.

I know there are external libraries (like Afero and MemFS), but I'd usually try to avoid adding dependencies.

I also know I can do this by creating a new interface and implementing all the methods that I care about (Open for fs.FS, ReadDir, etc...) by myself, but it seems like everything that I want to do is already done by embed.FS, except for the construction of the files.

My question is: is there a way to do this while re-using embed.FS? Can I create an embed.FS on the fly?

I can see that embed.FS has a files *[]file, but it's obviously private. I wonder if there's a way to create a new type and tell Go to "pretend this was created properly and just use it as an embed.FS".

答案1

得分: 3

embed.FS是一种特定的实现,用于读取嵌入在二进制文件中的文件 - 它不能用于在运行时构建的文件系统。

标准库中有一些fs.FS的实现可能适用于您的用例。您可以将文件处理为以下形式之一:

  1. 一个临时文件系统目录,并将其传递给os.DirFS
  2. 一个内存中的ZIP文件,并使用archive/zip.Reader作为fs.FS
  3. testing/fstest.MapFS。这实际上是为测试而设计的,但它确实存在。

就个人而言,我会在构建二进制文件之前通过go generate进行缩小,并使用embed.FS。这可以提供一个更小的二进制文件,启动时间和内存使用也更少。

如果需要在运行时修改文件,我会编写自己的fs.FS或引入一个依赖项。这不需要太多的代码。

英文:

embed.FS is a specific implementation for reading files embedded in the binary - it can't be used for filesystems built at runtime.

There are some fs.FS implementations in the standard library that may work for your use case. You could process your files into:

  1. A temporary filesystem directory and pass to os.DirFS.
  2. An in-memory ZIP file and use archive/zip.Reader as an fs.FS.
  3. testing/fstest.MapFS. This is really intended for testing, but it is there..

Personally, I'd would either:

  • Minify via go generate before building the binary and using embed.FS. This could provide a smaller binary with less startup time/memory usage.
  • Write my own fs.FS or pull in a dependency if the files need to be modified at runtime. It's not much code.

huangapple
  • 本文由 发表于 2022年4月1日 23:17:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/71709224.html
匿名

发表评论

匿名网友

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

确定