Go language has introduced a new standard library since version 1.16.embed
, static files can be introduced into binary files
instruction:/go:embed
A simple small example demonstrates the introduction of static files into golang's binary packaging product
Project structure
$ tree . ├── └── static └──
File content
Hello World!
1. Introduce the content of the static file to the variable
package main import ( "embed" "fmt" ) // Introduce the content of the static file to the variable content//go:embed static/ var content string // Note that this statement is needed. Although it is not used, you can introduce files in the entire directory.//go:embed static/* var tmplFS func main() { (content) }
Output
Hello World!
2. Introduce all files in the entire directory
package main import ( "embed" "fmt" ) //go:embed static/* var tmplFS func main() { // Read file content content, _ := ("static/") (string(content)) // Hello World! }
Copy the packaged product to any other directory to run, and you can also read the contents of the static file.
#Compilation$ go build # Copy to any other directory to run./main Hello World!
Need to note:
- To introduce a package
embed
-
//go:embed
It is a whole, and there cannot be spaces behind the double oblique rods, for example:// go:embed
It's invalid
Extension: In projects separated by front-end and back-end, the front-end packaging products can be embedded into golang's binary packaging products and released together.
This is the article about Golang's example code to introduce static files using embed. For more related contents of Golang embed static files, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!