Go Embed简明教程
Go Embed簡明教程
go語言程序都是編譯成二進制可執(zhí)行文件的,但是實際執(zhí)行時除了需要可執(zhí)行程序,還需要一些靜態(tài)文件,比如html模板等,于是就有人想如果Go官方能內(nèi)建支持就好了。2019末一個提案被提出 issue#35950,期望Go官方編譯器支持嵌入靜態(tài)文件。后來Russ Cox專門寫了一個設(shè)計文檔 Go command support for embedded static assets, 并最終實現(xiàn)了它。
-
需要注意的這個功能在go 1.16beta之后才支持
-
對于單個的文件,支持嵌入為字符串和 byte slice
-
對于多個文件和文件夾,支持嵌入為新的文件系統(tǒng)FS
-
比如導(dǎo)入 "embed"包,即使無顯式的使用
go:embed指令用來嵌入,必須緊跟著嵌入后的變量名
-
只支持嵌入為string, byte slice和embed.FS三種類型,這三種類型的別名(alias)和命名類型(如type S string)都不可以
嵌入為字符串
假設(shè)有一個文件test.txt文件內(nèi)容為hello world
如下代碼編譯之后s的值就變成了"hello world"
//go:embed test.txt var s string嵌入為byte slice
你還可以將文件的內(nèi)容嵌入為slice of byte,也就是一個字節(jié)數(shù)組
//go:embed test.txt var b []byte嵌入為fs.FS
甚至你可以嵌入為一個文件系統(tǒng),這種方式在嵌入多個文件的時候非常有用
支持嵌入多個文件如:
//go:embed test.txt hello.txt支持指定文件夾如:
//go:embed file/file.txt支持多行方式嵌入如:
//go:embed test.txt hello.txt //go:embed file/file.txt //go:embed test.txt hello.txt //go:embed file/file.txt var f embed.FS// 使用 // 嵌入為文件系統(tǒng) data, _ := f.ReadFile("test.txt") fmt.Println(string(data)) data, _ = f.ReadFile("hello.txt") fmt.Println(string(data))支持嵌入文件夾
//go:embed file var d embed.FS完整代碼實現(xiàn)
package mainimport ("embed"_ "embed""fmt" )//go:embed test.txt var s string//go:embed test.txt var b []byte//go:embed test.txt hello.txt //go:embed file/file.txt var f embed.FS//go:embed file var d embed.FS//go:embed file/*.txt var pre embed.FSfunc main() {// 直接嵌入fmt.Println(s)fmt.Println(b)// 嵌入為文件系統(tǒng)data, _ := f.ReadFile("test.txt")fmt.Println(string(data))data, _ = f.ReadFile("hello.txt")fmt.Println(string(data))// 嵌入的時候文件是啥,這里要對應(yīng)指定為相同的文件路徑data, _ = f.ReadFile("file/file.txt")fmt.Println(string(data))data, _ = d.ReadFile("file/file.txt")fmt.Println(string(data))data, _ = pre.ReadFile("file/name.txt")fmt.Println(string(data)) }關(guān)注公眾號一起學(xué)習(xí)新技術(shù)
總結(jié)
以上是生活随笔為你收集整理的Go Embed简明教程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【OJ】洛谷函数与结构体题单题解锦集
- 下一篇: 《大数据》2015年第3期“研究”——社