I wrote earlier about using Go-binData to package configuration files: Golang contains the Go Embed embed feature, which can replace Go-bindata to embed files into executable binaries. This article will introduce the Go Embed feature through examples, including:
- For individual files, embedding as is supported
string
或[]byte
- For multiple files and folders, embedding is supported as a new file system
embed.FS
- Underline import
embed
Package, call packageinit()
The function is initialized - use
//go:embed
Directive to embed, followed by the filename or directory name of the embed - Only embedding as is supported
string
,[]byte
和embed.FS
Three types of
The embeddedstring
The basic syntax is very simple, first importing the Embed package, then importing the corresponding file or directory structure into the corresponding variable using the instruction //go: Embed filename. For example, create a file version. TXT in the current directory and enter 0.0.1.
package main
import(_"embed"
"fmt"
)
//go:embed version.txt
var version string
func main(a) {
fmt.Printf("version: %q\n", version)
}
Copy the code
The embedded[]byte
package main
import(_"embed"
"fmt"
)
//go:embed version.txt
var vb []byte
func main(a) {
fmt.Printf("version %q\n".string(vb))
}
Copy the code
The embeddedembed.FS
To embed multiple files or directories, the Go: Embed directive can be written as one or more lines:
package main
import(_"embed"
"fmt"
)
//go:embed hello.txt world.txt
var f embed.FS
func main(a) {
data, _ := f.ReadFile("hello.txt")
fmt.Println(string(data))
}
Copy the code
There are three main methods for the embed.FS type:
func (f FS) Open(name string) (fs.File, error)
func (f FS) ReadDir(name string) ([]fs.DirEntry, error)
func (f FS) ReadFile(name string) ([]byte, error)
Copy the code
conclusion
Go Embed embed is awesome, so you don’t need to use Go-bindata to generate extra Go source files.