Home > database >  how to generate an embed.FS?
how to generate an embed.FS?

Time:04-03

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".

CodePudding user response:

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.
  •  Tags:  
  • go
  • Related