Package embed provides access to files embedded in the running Go program.
Go source files that import “embed” can use the //go:embed directive to initialize a variable of type string, []byte, or FS with the contents of files read from the package directory or subdirectories at compile time.
1 2 3 4 5
import _ "embed"
//go:embed hello.txt var s string print(s)
1 2 3 4 5
import _ "embed"
//go:embed hello.txt var b []byte print(string(b))
1 2 3 4 5 6
import"embed"
//go:embed hello.txt var f embed.FS data, _ := f.ReadFile("hello.txt") print(string(data))
embeded files must under current folder. any file outside current folder will fail, for example /root/somefile will not work.
"go:embed image/*" embeds all files under image/, including all file start with .dot and _underscore.
* will not recursive sub folders. so .dotfile and _underscore will not be embeded with image/subfolder/ sub folder.
"go:embed image/" or "go:embed image" embeds all file but ignored which start with .dot and _underscore.
symbolic links are not followed.
1 2 3 4 5 6 7 8 9 10 11
// embed multi files into a single filesystem //go:embed image/* template/* //go:embed html/index.html var content embed.FS
//go:embed image template html/index.html var content embed.FS
// embed files with space //go:embed "he llo.txt" var content embed.FS
Example with http-fileserver:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import ( "embed" "log" "net/http" )
//go:embed internal/embedtest/testdata/*.txt var content embed.FS