go:embed 指令
· 阅读需 2 分钟
[GoLang官方提案]https://go.googlesource.com/proposal/+/master/design/draft-embed.md
//go:embed 支持嵌入静态文件。
- 对于单个文件,可以嵌入为字符串和
byte slice - 多个文件,支持嵌入为新的文件系统 FS
- 只支持嵌入为
string,byte slice和embed.FS三种类型,这三种类型的别名(alias)和命名类型(如type S string)都不 可以
嵌入字符串
//go:embed hello.txt
var s string
嵌入为 byte slice
//go:embed hello.txt
var b []byte
嵌入为fs.FS
基本使用
//go:embed hello.txt
var f embed.FS
支持同一变量上嵌入多个文件
//go:embed hello1.txt
//go:embed hello2.txt
var f embed.FS
func main() {
data, _ := f.ReadFile("hello.txt")
fmt.Println(string(data))
data, _ = f.ReadFile("hello2.txt")
fmt.Println(string(data))
}
匹配模式
go:embed dirpath 次文件夹下的除了 . 和 _ 开头的文件/文件夹都会被嵌入(递归)。
如果要嵌入.和_开头的文件/文件夹,需要使用 go:embed dirpath/*。
注意:这个只能嵌入 dirpath 目录下的 .和_开头的文件/文件夹。子文件夹下的 . 和 _ 开头的文件/文件夹是不会嵌入。