Lee Benson
Lee Benson

Reputation: 11599

Golang - embedding filesystem in binary; using with libraries

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?

Upvotes: 1

Views: 1173

Answers (1)

fuz
fuz

Reputation: 93024

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.

Upvotes: 1

Related Questions