embed 资源嵌入
//go:embed 嵌入静态文件/模板、单二进制部署、go:generate 代码生成
embed 资源嵌入
Go 1.16+ 的 //go:embed 编译时把文件嵌入二进制——部署只需要一个可执行文件。
学完本章你将: 掌握 embed 静态文件/模板、go:generate 代码生成。
嵌入文件
go
package main
import (
"embed"
"fmt"
)
//go:embed hello.txt
var hello string // 嵌入单个文件为字符串
//go:embed config.json
var config []byte // 嵌入为字节切片
//go:embed static/*
var staticFiles embed.FS // 嵌入整个目录
func main() {
fmt.Println(hello)
// 读取嵌入的文件
data, _ := staticFiles.ReadFile("static/index.html")
fmt.Println(string(data))
// 作为 HTTP 文件服务器
http.Handle("/static/", http.FileServer(http.FS(staticFiles)))
}
嵌入模板
go
//go:embed templates/*
var templates embed.FS
func main() {
tmpl := template.Must(
template.ParseFS(templates, "templates/*.html"),
)
tmpl.Execute(w, data)
}
go:generate —— 代码生成
go
//go:generate stringer -type=Status
type Status int
const (
Pending Status = iota
Approved
Rejected
)
// 运行 go generate → 自动生成 status_string.go
// 包含 func (Status) String() string