In this post, I will show you a tip to embed files in Go (golang), which, in facts, reads file contents into a variable.
Starting from Go 1.16+, Go developers can easily read files using the embed
package, which saves file contents into string
, []byte
or embed.FS
format.
Let say, there has this file data.txt
in current directory:
this file content should be embedded in go program
We then can use embed to read this file content as following:
package main
import _ "embed"
//go:embed "data.txt"
var contents string
func main() {
println(contents)
}
The instruction go:embed "data"
says that, we would like to read whole file content and store into the below declared variable contents
which has string
type.
Similarly, we can store contents file byte array []byte
like so:
package main
import _ "embed"
//go:embed "data.txt"
var contents []byte
func main() {
println(string(contents))
}
For a better trick, if there are many files in a directory, we can read them all into a embed.FS
variable, then access them as necessary.
For example, we have a directory named data
which contains two data files companies.txt
and countries.txt
. We will access and read their contents like this:
package main
import (
"embed"
_ "embed"
)
//go:embed "data/*"
var fs embed.FS
func main() {
companies, _ := fs.ReadFile("data/companies.txt")
println("Companies: \n" + string(companies))
countries, _ := fs.ReadFile("data/countries.txt")
println("Countries: \n" + string(countries))
}
That’s how you embed files in Go. Have fun!