Thursday, 19 June 2025

Go embed * go by default exclude .go file during go build

 https://stackoverflow.com/questions/56608186/does-go-build-include-non-go-files-in-binary

Does go build includes non go files in binary?

By default, no: you need to embed them.


GO:EMBED:

When using go:embed to embed files or directories in a Go application, the path to access the embedded content within the embed.FS will be relative to the directory containing the source file where the //go:embed directive is declared.
Here's how the path is determined:
  • Relative to the package directory:
    The patterns specified in the //go:embed directive are interpreted as paths relative to the directory of the Go source file containing the directive.
  • Embedded structure:
    If you embed a directory, the files within that directory and its subdirectories will maintain their relative path structure within the embed.FS.
  • Accessing files:
    When you later access these embedded files using methods like embed.FS.ReadFile() or embed.FS.Open(), you will use paths that reflect this embedded structure.
Example:
Consider a file main.go in the root of your project, and a static directory with a css subdirectory containing style.css:
myproject/
├── main.go
└── static/
    └── css/
        └── style.css
main.go
package main

import (
"embed"
)

//go:embed static/*
var staticFS embed.FS

func main() {
// To access style.css, the path will be "static/css/style.css"
// relative to the embedded root.
content, err := staticFS.ReadFile("static/css/style.css")
if err != nil {
// Handle error
}
// Use content
}



No comments:

Post a Comment