Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
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.
The "embed" package does not work with the Gophernotes kernel (for Jupyter/Lab notebooks).
.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.You can embed multiple files as one variable using wildcards.
You can embed a whole directory as a variable of
embed.FSand then use it access a single file as needed at runtime. Below is an example of embedding a directory nameddataas aembed.FSvariable namedData.//go:embed data var Data embed.FSBy 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.FSIt does not make much sense to read the file mode of an embeded file.
- Invoking
os.Staton an embeded file results in an error. You have to open an embeded file usingembed.FS.Openand then use th methodFile.Modeto get the mode of the embeded file. However, the file mode of an embeded file is always444. - When embedding a file, the mode of the original file will be lost.
- Invoking
import _ "embed"
//go:embed hello.txt
var s string
print(s)
import _ "embed"
//go:embed hello.txt
var b []byte
print(string(b))
import "embed"
//go:embed hello.txt
var f embed.FS
data, _ := f.ReadFile("hello.txt")
print(string(data))