别着急,坐和放宽
使用社交账号登录
embed、io/fs、net/http 即可使用。嵌入单个文本文件为字符串:
package main
import (
_ "embed"
"fmt"
)
//go:embed message.txt
var message string
func main() {
fmt.Println(message)
}
嵌入目录并读取文件(以嵌入根为基准路径):
package main
import (
"embed"
"fmt"
)
//go:embed static
var staticFiles embed.FS
func main() {
data, _ := staticFiles.ReadFile("static/index.html")
fmt.Println(string(data))
}
使用通配符一次性嵌入多文件:
package main
import (
"embed"
"fmt"
)
//go:embed templates/*.html partials/*.html
var tmplFS embed.FS
func main() {
entries, _ := tmplFS.ReadDir("templates")
for _, e := range entries {
b, _ := tmplFS.ReadFile("templates/" + e.Name())
fmt.Printf("Loaded %s (%d bytes)\n", e.Name(), len(b))
}
}
package main
import (
"embed"
"net/http"
)
//go:embed static/*
var assets embed.FS
func main() {
http.Handle("/", http.FileServer(http.FS(assets)))
http.ListenAndServe(":8080", nil)
}
运行后在 http://localhost:8080 直接访问嵌入的静态文件,无需额外拷贝。
package main
import (
_ "embed"
"fmt"
)
//go:embed image.webp
var img []byte
func main() {
fmt.Printf("Image size: %d bytes\n", len(img))
}
当资源非 UTF-8 文本时,使用 []byte 可以避免编码问题。
//go:embed 的路径与模式必须为相对路径,基于“声明该变量的源文件所在目录”。不支持绝对路径。/,即使在 Windows。示例:"static/index.html"。filepath.Match 语义),如 static/*、templates/*.html。可以在同一指令中列出多个模式。..,不可引用包目录之外的文件。string(文本)、[]byte(二进制)、embed.FS(多文件/目录)。embed.FS 时,ReadFile 的路径以嵌入根为基准;若嵌入的是目录 static,读取应为 static/xxx。结论:
string,二进制用 []byte;多文件/目录用 embed.FS。/;不要混用反斜杠 \。//go:embed 必须紧邻变量声明;变量类型仅支持 string、[]byte、embed.FS。embed.FS,减少散乱的变量。go:embed 让资源管理从“运行期找文件”变为“编译期打包”。掌握“相对路径、统一分隔符、类型选择”这三点,就能在 CLI、Web 服务、微服务工具中干净地管理静态与模板资源,极大简化部署与加载流程。
package main
import (
"embed"
"html/template"
"net/http"
)
//go:embed templates/*.html
var views embed.FS
func main() {
t := template.Must(template.ParseFS(views, "templates/*.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_ = t.ExecuteTemplate(w, "home.html", map[string]string{"Title": "Embed Demo"})
})
_ = http.ListenAndServe(":8080", nil)
}