Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Sunday, October 12, 2025

GO Embed

 



In this post we review the GO embed annotation and its implications.


Sample Code


package main

import (
"embed"
_ "embed"
"fmt"
)

//go:embed hello.txt
var textFile string

//go:embed hello.txt
var binaryFile []byte

//go:embed data1 data2
var files embed.FS

func main() {
fmt.Printf("%v bytes:\n%v\n", len(binaryFile), textFile)

entries, err := files.ReadDir(".")
if err != nil {
panic(err)
}
for _, entry := range entries {
fmt.Printf("%v dir: %v\n", entry.Name(), entry.IsDir())
}
}


Implications

The GO embed is a simple way of adding files as part of the GO compiled output binary. It serves as an aletnative to making this files available to the application in other mannger, such as supplying the files as part of a docker image, or mounting the files using a kubernetes ConfigMap.

Notice the files are added as part of the binary, so embedding large files means a larger output binary.


Embed Methods

The are 3 methods to embed a file.

First we can add a file as a string. In such a case we should add the explicit embed import:

_ "embed"


Second we can add the file as bytes array, this is very similar to the first method.


Third we can include a set of folders as a virtual file system. The annotation includes the list of folders to be included. There are special handling for files starting with a dot, see more about this in here.


Final Note

While embed is a simple way to add files, it should be used only if we're sure we will not want to change the files in an active running deployment.






No comments:

Post a Comment