[Go] embed指令嵌入静态文件到二进制包
2023-02-18 15:41:16 时间
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, })
相关文章
- 云图说|初识数据库和应用迁移UGO
- 华为云UGO:醒醒!你的异构数据库迁移难题有救了
- 华为云UGO正式公测:4大核心优势破解异构数据库迁移难题
- MongoDB 事务,复制和分片的关系
- 【经验之谈】Git使用之Windows环境下配置
- git clone开启云上AI开发
- 实践GoF的设计模式:代理模式
- Ubuntu & GitLab CI & Docker & ASP.NET Core 2.0 自动化发布和部署(1)
- 初学开发必看:何为Git,何为SVN
- 实践GoF的设计模式:访问者模式
- 【经验之谈】Git使用之TortoiseGit配置VS详解
- cmder git bash 使用
- 4步教你学会使用Linux-Audit工具
- 10种有用的Linux Bash_Completion 命令示例
- Ubuntu & GitLab CI & Docker & ASP.NET Core 2.0 自动化发布和部署(2)
- 实践GoF的设计模式:迭代器模式
- 【补充】Gitlab 部署 CI 持续集成
- Google Chrome 应用商店上传扩展程序
- 实践GoF的23种设计模式:观察者模式
- Ubuntu Docker 安装和配置 GitLab CI 持续集成