[Go] embed指令嵌入静态文件到二进制包

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,
    })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值