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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM