go 1.16开始提供了embed指令 , 可以将静态资源嵌入到编译包里面
这样就可以把网页模板等文件直接打包了,就不需要每次还要拷贝静态文件
常规用法:
import _ "embed"
//go:embed hello.txt
var s string
func main() {
print(s)
}
作为一个文件路径,也支持多个,以及通配符
//go:embed hello1.txt hello2.txt
var f embed.FS
func main() {
data1, _ := f.ReadFile("hello1.txt")
fmt.Println(string(data1))
data2, _ := f.ReadFile("hello2.txt")
fmt.Println(string(data2))
}
但是
路径里面不能包含 . .. 这种相对路径的符号否则报错 , 也不能以/ 开头
这就意味着 , 如果模板文件在单独的目录里 , 那么需要有个go的包以及go文件对外提供全局变量
类似我这样
package static
import "embed"
//go:embed templates/*
var TemplatesEmbed embed.FS
//go:embed js/*
var JsEmbed embed.FS
如果与gin的模板渲染配合使用
templ := template.Must(template.New("").ParseFS(static.TemplatesEmbed,"templates/*.html"))
engine.SetHTMLTemplate(templ)
渲染模板的时候就可以直接来 , 模板的路径是在 ./static/templates/index.html
c.HTML(http.StatusOK, "index.html", gin.H{
"Title": title,
})

Go 1.16 引入了embed指令,允许开发者将静态文件如网页模板直接嵌入到二进制包中,避免了运行时手动拷贝静态文件的需求。使用时需注意,文件路径不能包含相对路径符号如 . 或 ..,也不能以 / 开头。若静态文件位于独立目录,需创建相应Go包和文件定义全局变量。当与 Gin 框架结合使用时,模板渲染变得更直接,例如引用 ./static/templates/index.html。
5301

被折叠的 条评论
为什么被折叠?



