embed 嵌入檔案

最後更新


本頁說明如何用 //go:embed 把檔案直接打包進執行檔,以 string、[]byte 或 embed.FS 取用,並搭配 http.FileServerFS 提供靜態網頁。

為什麼要嵌入檔案


程式常需要一些非 Go 的檔案:設定檔範本、HTML、CSS、SQL、版本號。如果這些檔案和執行檔分開放,部署時就得記得一起複製,路徑還可能因為工作目錄不同而找不到。
嵌入(embed,Go 1.16 起)讓編譯器在 go build 時把檔案內容一起放進執行檔。部署時只要複製一個執行檔,檔案永遠找得到。可以想成「把附件直接釘在信紙上」,不怕寄丟。
用法是在套件層級的變數上方寫一行 //go:embed 路徑,變數型別決定拿到什麼:
變數型別可嵌入適合
string單一檔案文字內容,例如版本號、SQL
[]byte單一檔案二進位或要交給解析器的內容
embed.FS多個檔案或整個目錄網頁靜態檔、範本目錄

規則:
  • //go:embed 要緊接在變數宣告上方,中間只能有空行或 // 註解;// 與 go:embed 之間不能有空白,否則會被當成普通註解而不生效
  • 路徑相對於該 .go 檔所在目錄,用 / 分隔,不能用 .. 往上層,也不能跨出 module
  • 用 string 或 []byte 時,必須匯入 embed 套件;沒用到它的名稱,就寫成空白匯入 _ "embed"(見套件與匯入)

embed 套件的 API 細節見 embed。

嵌入成 string


最簡單的用法:把一個文字檔讀成字串。下面把 version.txt 嵌入,執行時不再需要這個檔案。
檔案樹:
  1. embedstr/
  2. ├── go.mod
  3. ├── main.go
  4. └── version.txt

version.txt(內容是一行 v1.4.2,結尾有換行):
  1. v1.4.2

main.go:
  1. package main
  2. import (
  3. _ "embed"
  4. "fmt"
  5. "strings"
  6. )
  7. //go:embed version.txt
  8. var version string
  9. func main() {
  10. fmt.Printf("%q\n", version)
  11. fmt.Println("version:", strings.TrimSpace(version))
  12. }

執行:
  1. $ go run .

輸出:
  1. "v1.4.2\n"
  2. version: v1.4.2

嵌入的內容和檔案一模一樣,包括結尾的換行,所以常搭配 strings.TrimSpace 使用。

嵌入成 []byte


需要把內容交給 json.Unmarshal 這類吃 []byte 的函式,或是圖片等二進位檔時,用 []byte 比較方便。下面嵌入預設設定檔並解析(JSON 用法見 JSON)。
檔案樹:
  1. embedbytes/
  2. ├── go.mod
  3. ├── config.json
  4. └── main.go

config.json:
  1. {"port": 8080, "debug": true}

main.go:
  1. package main
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "fmt"
  6. )
  7. //go:embed config.json
  8. var configData []byte
  9. type Config struct {
  10. Port int `json:"port"`
  11. Debug bool `json:"debug"`
  12. }
  13. func main() {
  14. fmt.Println("bytes:", len(configData))
  15. var cfg Config
  16. if err := json.Unmarshal(configData, &cfg); err != nil {
  17. fmt.Println("parse error:", err)
  18. return
  19. }
  20. fmt.Printf("%+v\n", cfg)
  21. }

執行:
  1. $ go run .

輸出:
  1. bytes: 30
  2. {Port:8080 Debug:true}

注意:嵌入的 string/[]byte 在編譯時就固定了,修改原始檔案後要重新編譯才會生效。[]byte 雖然可以修改,但改的只是記憶體中的副本,不會寫回任何檔案。

embed.FS 嵌入多個檔案


要嵌入一整個目錄或多個檔案時,用 embed.FS。它是一個唯讀的虛擬檔案系統,實作了 io/fs 的 fs.FS 介面(見 io/fs),所以能交給所有接受 fs.FS 的函式,例如 fs.WalkDir、template.ParseFS。
一行 //go:embed 可以寫多個路徑(用空白分隔),也可以使用 * 這類萬用字元。
方法作用
ReadFile(name)讀取單一檔案的完整內容
ReadDir(name)列出目錄內容
Open(name)開啟檔案,回傳 fs.File

檔案樹:
  1. embedfs/
  2. ├── go.mod
  3. ├── main.go
  4. ├── notes.txt
  5. └── templates/
  6. ├── .draft.tmpl
  7. ├── bye.tmpl
  8. ├── hello.tmpl
  9. └── mail/
  10. └── welcome.tmpl

templates/hello.tmpl:
  1. Hello, {{.}}!

templates/bye.tmpl:
  1. Bye, {{.}}.

templates/mail/welcome.tmpl:
  1. Welcome mail for {{.}}

templates/.draft.tmpl 內容為 secret,notes.txt 內容為 notes(各一行)。
main.go:
  1. package main
  2. import (
  3. "embed"
  4. "fmt"
  5. "io/fs"
  6. "os"
  7. "text/template"
  8. )
  9. //go:embed templates notes.txt
  10. var files embed.FS
  11. func main() {
  12. fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
  13. if err != nil {
  14. return err
  15. }
  16. fmt.Println(path, d.IsDir())
  17. return nil
  18. })
  19. data, err := files.ReadFile("notes.txt")
  20. if err != nil {
  21. fmt.Println("read error:", err)
  22. return
  23. }
  24. fmt.Printf("notes.txt: %q\n", data)
  25. _, err = files.ReadFile("missing.txt")
  26. fmt.Println("missing:", err)
  27. t := template.Must(template.ParseFS(files, "templates/*.tmpl"))
  28. t.ExecuteTemplate(os.Stdout, "hello.tmpl", "gopher")
  29. t.ExecuteTemplate(os.Stdout, "bye.tmpl", "gopher")
  30. }

執行:
  1. $ go run .

輸出:
  1. . true
  2. notes.txt false
  3. templates true
  4. templates/bye.tmpl false
  5. templates/hello.tmpl false
  6. templates/mail true
  7. templates/mail/welcome.tmpl false
  8. notes.txt: "notes\n"
  9. missing: open missing.txt: file does not exist
  10. Hello, gopher!
  11. Bye, gopher.

幾個觀察:
  • embed.FS 裡的路徑保留原本的目錄結構,templates/hello.tmpl 不會被攤平成 hello.tmpl
  • 嵌入目錄時會遞迴包含子目錄,但 .draft.tmpl 不見了,原因見下一節
  • 讀不存在的檔案回傳錯誤,可用 errors.Is(err, fs.ErrNotExist) 判斷

隱藏檔與 all: 前綴


嵌入「目錄」時,Go 會略過名稱以 . 或 _ 開頭的檔案,避免不小心把 .git、.env 這類檔案打包進去。想要一起包含時有兩種寫法:
寫法結果
//go:embed templates略過 . 和 _ 開頭的檔案
//go:embed all:templates全部包含
//go:embed templates/*萬用字元直接比對到的檔案全部包含(但更深層子目錄裡的仍會略過)

檔案樹:
  1. embedall/
  2. ├── go.mod
  3. ├── main.go
  4. └── templates/
  5. ├── .draft.tmpl
  6. ├── _wip.tmpl
  7. └── hello.tmpl

main.go:
  1. package main
  2. import (
  3. "embed"
  4. "fmt"
  5. "io/fs"
  6. )
  7. //go:embed templates
  8. var normal embed.FS
  9. //go:embed all:templates
  10. var everything embed.FS
  11. //go:embed templates/*
  12. var star embed.FS
  13. func list(name string, fsys fs.FS) {
  14. matches, err := fs.Glob(fsys, "templates/*")
  15. if err != nil {
  16. fmt.Println(name, "error:", err)
  17. return
  18. }
  19. fmt.Println(name, matches)
  20. }
  21. func main() {
  22. list("normal: ", normal)
  23. list("all: ", everything)
  24. list("templates/*", star)
  25. }

執行:
  1. $ go run .

輸出:
  1. normal: [templates/hello.tmpl]
  2. all: [templates/.draft.tmpl templates/_wip.tmpl templates/hello.tmpl]
  3. templates/* [templates/.draft.tmpl templates/_wip.tmpl templates/hello.tmpl]

注意://go:embed 的錯誤都在編譯時就會被抓出來。路徑比對不到任何檔案時:
  1. main.go:8:12: pattern missing.txt: no matching files found

把 //go:embed 寫在函式裡的區域變數上時:
  1. ./main.go:9:4: go:embed cannot apply to var inside func

搭配 http.FileServerFS


embed.FS 最常見的用途是把網站的 HTML、CSS、JavaScript 打包進伺服器程式。Go 1.22 起,http.FileServerFS 可以直接把任何 fs.FS 變成提供靜態檔案的 HTTP handler(HTTP 伺服器見 net/http)。
簽名:
  1. func FileServerFS(root fs.FS) Handler
  2. func Sub(fsys FS, dir string) (FS, error)

嵌入 static 目錄後,檔案在 embed.FS 裡的路徑是 static/index.html。如果直接交給 FileServerFS,網址也得寫成 /static/index.html。用 fs.Sub 取出 static 這個子目錄當作根,網址就變成 /index.html。
下面用 httptest 起一個本機測試伺服器(見 net/http/httptest)來發送請求。
檔案樹:
  1. embedweb/
  2. ├── go.mod
  3. ├── main.go
  4. └── static/
  5. ├── index.html
  6. └── css/
  7. └── site.css

static/index.html:
  1. <h1>Hello embed</h1>

static/css/site.css:
  1. h1 { color: teal; }

main.go:
  1. package main
  2. import (
  3. "embed"
  4. "fmt"
  5. "io"
  6. "io/fs"
  7. "net/http"
  8. "net/http/httptest"
  9. )
  10. //go:embed static
  11. var staticFiles embed.FS
  12. func main() {
  13. root, err := fs.Sub(staticFiles, "static")
  14. if err != nil {
  15. fmt.Println("sub error:", err)
  16. return
  17. }
  18. mux := http.NewServeMux()
  19. mux.Handle("GET /", http.FileServerFS(root))
  20. srv := httptest.NewServer(mux)
  21. defer srv.Close()
  22. for _, path := range []string{"/", "/css/site.css", "/missing.txt"} {
  23. resp, err := http.Get(srv.URL + path)
  24. if err != nil {
  25. fmt.Println("request error:", err)
  26. return
  27. }
  28. body, _ := io.ReadAll(resp.Body)
  29. resp.Body.Close()
  30. fmt.Printf("%s -> %d %s\n%s", path, resp.StatusCode, resp.Header.Get("Content-Type"), body)
  31. }
  32. }

執行:
  1. $ go run .

輸出:
  1. / -> 200 text/html; charset=utf-8
  2. <h1>Hello embed</h1>
  3. /css/site.css -> 200 text/css; charset=utf-8
  4. h1 { color: teal; }
  5. /missing.txt -> 404 text/plain; charset=utf-8
  6. 404 page not found

請求 / 時,FileServerFS 自動回傳目錄裡的 index.html;Content-Type 依副檔名判斷;找不到的檔案回 404。實際上線時把 httptest.NewServer 換成 http.ListenAndServe(":8080", mux) 即可。

重點整理


  • //go:embed 路徑 寫在套件層級變數上方,編譯時把檔案打包進執行檔(Go 1.16 起)
  • 單一檔案用 string 或 []byte(需 _ "embed"),多個檔案或目錄用 embed.FS
  • 嵌入目錄會略過 .、_ 開頭的檔案,要包含就加 all: 前綴
  • 路徑比對不到檔案、寫在函式內都會編譯失敗,問題不會拖到執行時才發現
  • fs.Sub 去掉目錄前綴,再交給 http.FileServerFS(Go 1.22 起)就能提供靜態網站

資料來源