//go:embed static/* var staticFiles embed.FS
//go:embed logo.png var logoBytes []byte
This is the most common "file link" in modern Go—it links external files into your executable at compile time. Basic usage package main import _ "embed" go file links
Create a hard link err := os.Link("original.txt", "hardlink.txt") Check if two files are hard-linked s1, _ := os.Stat("file1.txt") s2, _ := os.Stat("file2.txt") if os.SameFile(s1, s2) fmt.Println("Same file (hard link)")
func main() data, _ := staticFiles.ReadFile("static/style.css") log.Println(string(data)) //go:embed static/* var staticFiles embed
Often you just need to reference files with paths. Use filepath.Join for cross-platform import "path/filepath" path := filepath.Join("data", "users", "profile.json") Get executable directory (to find linked assets) exePath, _ := os.Executable() dir := filepath.Dir(exePath) configPath := filepath.Join(dir, "configs", "app.yaml") Go module-aware paths (for testdata) // In a test: paths are relative to test file data, _ := os.ReadFile("testdata/input.txt") 5. Go generate – Link code generation to files Use //go:generate to run tools that transform external files into Go code.
//go:embed templates/*.html var templateFS embed.FS package main import ( "embed" "log" ) Go generate – Link code generation to files
//go:generate stringer -type=Pill //go:generate go-bindata -o static.go static/ Run with: