If you want to directly import a configuration file, for example, you would simply add a line comment with the prefix go:embed
followed by the file name:
// main.go
package main
import (
"fmt"
_ "embed"
)
//go:embed env
var env string
func main() {
fmt.Println(env)
}
where env
has the following content
# env
FOO = BAR
would print the content of env
without having to add code to open the corresponding file and reading it into a string.
Try it with go run
:
$ go run main.go
FOO = BAR
This only works for paths in the same directory or in sub-directory as the source file declaring the file embedding. Files in ancestor directories may not be embedded since the patterns do not allow the .
or ..
path elements.