Ben Chuanlong Du's Blog

It is never too late to learn.

Embed File in Golang Binary

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

  1. My understanding is that embeded files are loaded into memory, which means that the Go app might consume large memory if you embed a large file.

  2. The "embed" package does not work with the Gophernotes kernel (for Jupyter/Lab notebooks).

  3. . and .. are disallowed in the path of a embed path, which means that you can only embed files in the current directory or its subdirectories. In another words, However, a embed variable can be used imported into other modules.

  4. You can embed multiple files as one variable using wildcards.

  5. You can embed a whole directory as a variable of embed.FS and then use it access a single file as needed at runtime. Below is an example of embedding a directory named data as a embed.FS variable named Data.

     //go:embed data
     var Data embed.FS
    
    

    By default, hidden files are ignore. However, you can specify the prefix all: to embed hidden files as well.

     //go:embed all:data
     var Data embed.FS
  6. It does not make much sense to read the file mode of an embeded file.

    • Invoking os.Stat on an embeded file results in an error. You have to open an embeded file using embed.FS.Open and then use th method File.Mode to get the mode of the embeded file. However, the file mode of an embeded file is always 444.
    • When embedding a file, the mode of the original file will be lost.
In [3]:
import _ "embed"

//go:embed hello.txt
var s string
print(s)
In [4]:
import _ "embed"

//go:embed hello.txt
var b []byte
print(string(b))
In [6]:
import "embed"

//go:embed hello.txt
var f embed.FS
data, _ := f.ReadFile("hello.txt")
print(string(data))
In [ ]:
 

Comments