在go官方出嵌入文件的方法前我在網(wǎng)上找過,并且自己還研究過,雖然沒有問題,但是既然官方支持還是用起來吧。
看了下go源碼embed/embed.go
很簡單,并且看embed/internal/embedtest/embed_test.go
就知道如何使用。
原理是使用go:embed
標(biāo)簽來完成。下面是直接讀取文件內(nèi)容,需要注意下面幾點(diǎn)。
文件不是utf8
編碼時(shí),輸出內(nèi)容為中文會(huì)亂碼。
測試過嵌入文件只能為源碼文件同級目錄和子目錄下的文件,試過其他目錄的絕對路徑或相對路徑會(huì)報(bào)錯(cuò)。
我測試過幾個(gè)能想到的場景,有些會(huì)報(bào)錯(cuò),所以在使用時(shí)需要注意。
package main import ( _ "embed" ) //go:embed test.txt var testString string // 當(dāng)前目錄,解析為string類型 //go:embed test.txt var testByte []byte // 當(dāng)前目錄,解析為[]byte類型 //go:embed test/test.txt var testAbsolutePath string // 子目錄,解析為string類型 //go:embed notExistsFile var testErr0 string // 文件不存在,編譯報(bào)錯(cuò):pattern notExistsFile: no matching files found //go:embed dir var testErr1 string // dir是目錄,編譯報(bào)錯(cuò):pattern dir: cannot embed directory dir: contains no embeddable files //go:embed ../test.txt var testErr2 string // 相對路徑,不是當(dāng)前目錄或子目錄,編譯報(bào)錯(cuò):pattern ../test.txt: invalid pattern syntax //go:embed D:\test.txt var testErr3 string // 絕對路徑,編譯報(bào)錯(cuò):pattern D:\test.txt: no matching files found func main() { println(testString) println(string(testByte)) println(testAbsolutePath) }
package main import ( "embed" "io" "os" ) //go:embed test0.txt test1.txt test1*.txt //go:embed test/test0.txt test/test1.txt //go:embed test0 var fileList embed.FS /* 使用上述方法可以將多個(gè)文件或目錄添加到fileList中。 1. 添加多個(gè)文件,且支持"*"號通配文件。 2. 支持子目錄文件。 3. 支持嵌入一個(gè)目錄。 */ func main() { testDir, err := fileList.ReadDir("test0") if err != nil { panic(err) } for _, v := range testDir { println(v.Name()) // 打印嵌入的目錄內(nèi)容 } // 使用fileList.Open可以生成一個(gè)對象,可以通過文件流那樣讀出來 testFile, err := fileList.Open("test0.txt") if err != nil { panic(err) } io.Copy(os.Stdout, testFile) testFile, err = fileList.Open("test112.txt") if err != nil { panic(err) } io.Copy(os.Stdout, testFile) testFile, err = fileList.Open("test/test1.txt") if err != nil { panic(err) } io.Copy(os.Stdout, testFile) // 直接將文件內(nèi)容讀出來 data, err := fileList.ReadFile("test111.txt") if err != nil { panic(err) } println(string(data)) }
今天看到go1.16發(fā)布,看了下特性,支持嵌入文件到可執(zhí)行程序中,所以研究了一下。
我發(fā)現(xiàn)直接看源碼的_test測試文件就知道是如何使用的,都不需要到處搜教程。
所以說學(xué)習(xí)要知其然且知其所以然,不然天天搜別人的示例代碼,卻不知道原理,是不能靈活使用的。
到此這篇關(guān)于golang官方嵌入文件到可執(zhí)行程序的文章就介紹到這了,更多相關(guān)golang嵌入文件到可執(zhí)行程序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:儋州 西雙版納 青海 海南 遼寧 安康 物業(yè)服務(wù) 電子產(chǎn)品
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《golang官方嵌入文件到可執(zhí)行程序的示例詳解》,本文關(guān)鍵詞 golang,官方,嵌入,文件,到,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。