网站在线客服系统GOFLY代码开发日志-8:使用embed打包静态模板资源

在使用golang开发网站在线客服系统GOFLY应用的时候,网站的静态模板资源是需要和二进制一块上传到服务器,这样才能加载到模板文件。每次请求执行url的时候,都需要去读取文件并渲染显示出来。

在golang1.16版本以后,增加了embed指令可以把静态资源一块打包到二进制文件里面去,这样就可以只上传一个二进制文件,就能运行渲染页面,也保护了源码的安全。

下面是常规用法,把hello.txt打包进字符串变量里

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,
    })

后面还遇到了哪些问题和知识点将会继续进行总结。

演示网站:
gofly.sopans.com

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!