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 嵌入,執行時不再需要這個檔案。檔案樹:
- embedstr/
- ├── go.mod
- ├── main.go
- └── version.txt
version.txt(內容是一行 v1.4.2,結尾有換行):- v1.4.2
main.go:- package main
- import (
- _ "embed"
- "fmt"
- "strings"
- )
- //go:embed version.txt
- var version string
- func main() {
- fmt.Printf("%q\n", version)
- fmt.Println("version:", strings.TrimSpace(version))
- }
執行:
- $ go run .
輸出:
- "v1.4.2\n"
- version: v1.4.2
嵌入的內容和檔案一模一樣,包括結尾的換行,所以常搭配
strings.TrimSpace 使用。嵌入成 []byte
需要把內容交給
json.Unmarshal 這類吃 []byte 的函式,或是圖片等二進位檔時,用 []byte 比較方便。下面嵌入預設設定檔並解析(JSON 用法見 JSON)。檔案樹:
- embedbytes/
- ├── go.mod
- ├── config.json
- └── main.go
config.json:- {"port": 8080, "debug": true}
main.go:- package main
- import (
- _ "embed"
- "encoding/json"
- "fmt"
- )
- //go:embed config.json
- var configData []byte
- type Config struct {
- Port int `json:"port"`
- Debug bool `json:"debug"`
- }
- func main() {
- fmt.Println("bytes:", len(configData))
- var cfg Config
- if err := json.Unmarshal(configData, &cfg); err != nil {
- fmt.Println("parse error:", err)
- return
- }
- fmt.Printf("%+v\n", cfg)
- }
執行:
- $ go run .
輸出:
- bytes: 30
- {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 |
檔案樹:
- embedfs/
- ├── go.mod
- ├── main.go
- ├── notes.txt
- └── templates/
- ├── .draft.tmpl
- ├── bye.tmpl
- ├── hello.tmpl
- └── mail/
- └── welcome.tmpl
templates/hello.tmpl:- Hello, {{.}}!
templates/bye.tmpl:- Bye, {{.}}.
templates/mail/welcome.tmpl:- Welcome mail for {{.}}
templates/.draft.tmpl 內容為 secret,notes.txt 內容為 notes(各一行)。main.go:- package main
- import (
- "embed"
- "fmt"
- "io/fs"
- "os"
- "text/template"
- )
- //go:embed templates notes.txt
- var files embed.FS
- func main() {
- fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
- fmt.Println(path, d.IsDir())
- return nil
- })
- data, err := files.ReadFile("notes.txt")
- if err != nil {
- fmt.Println("read error:", err)
- return
- }
- fmt.Printf("notes.txt: %q\n", data)
- _, err = files.ReadFile("missing.txt")
- fmt.Println("missing:", err)
- t := template.Must(template.ParseFS(files, "templates/*.tmpl"))
- t.ExecuteTemplate(os.Stdout, "hello.tmpl", "gopher")
- t.ExecuteTemplate(os.Stdout, "bye.tmpl", "gopher")
- }
執行:
- $ go run .
輸出:
- . true
- notes.txt false
- templates true
- templates/bye.tmpl false
- templates/hello.tmpl false
- templates/mail true
- templates/mail/welcome.tmpl false
- notes.txt: "notes\n"
- missing: open missing.txt: file does not exist
- Hello, gopher!
- 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/* | 萬用字元直接比對到的檔案全部包含(但更深層子目錄裡的仍會略過) |
檔案樹:
- embedall/
- ├── go.mod
- ├── main.go
- └── templates/
- ├── .draft.tmpl
- ├── _wip.tmpl
- └── hello.tmpl
main.go:- package main
- import (
- "embed"
- "fmt"
- "io/fs"
- )
- //go:embed templates
- var normal embed.FS
- //go:embed all:templates
- var everything embed.FS
- //go:embed templates/*
- var star embed.FS
- func list(name string, fsys fs.FS) {
- matches, err := fs.Glob(fsys, "templates/*")
- if err != nil {
- fmt.Println(name, "error:", err)
- return
- }
- fmt.Println(name, matches)
- }
- func main() {
- list("normal: ", normal)
- list("all: ", everything)
- list("templates/*", star)
- }
執行:
- $ go run .
輸出:
- normal: [templates/hello.tmpl]
- all: [templates/.draft.tmpl templates/_wip.tmpl templates/hello.tmpl]
- templates/* [templates/.draft.tmpl templates/_wip.tmpl templates/hello.tmpl]
注意:
//go:embed 的錯誤都在編譯時就會被抓出來。路徑比對不到任何檔案時:- main.go:8:12: pattern missing.txt: no matching files found
把
//go:embed 寫在函式裡的區域變數上時:- ./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)。簽名:
- func FileServerFS(root fs.FS) Handler
- 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)來發送請求。檔案樹:
- embedweb/
- ├── go.mod
- ├── main.go
- └── static/
- ├── index.html
- └── css/
- └── site.css
static/index.html:- <h1>Hello embed</h1>
static/css/site.css:- h1 { color: teal; }
main.go:- package main
- import (
- "embed"
- "fmt"
- "io"
- "io/fs"
- "net/http"
- "net/http/httptest"
- )
- //go:embed static
- var staticFiles embed.FS
- func main() {
- root, err := fs.Sub(staticFiles, "static")
- if err != nil {
- fmt.Println("sub error:", err)
- return
- }
- mux := http.NewServeMux()
- mux.Handle("GET /", http.FileServerFS(root))
- srv := httptest.NewServer(mux)
- defer srv.Close()
- for _, path := range []string{"/", "/css/site.css", "/missing.txt"} {
- resp, err := http.Get(srv.URL + path)
- if err != nil {
- fmt.Println("request error:", err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Printf("%s -> %d %s\n%s", path, resp.StatusCode, resp.Header.Get("Content-Type"), body)
- }
- }
執行:
- $ go run .
輸出:
- / -> 200 text/html; charset=utf-8
- <h1>Hello embed</h1>
- /css/site.css -> 200 text/css; charset=utf-8
- h1 { color: teal; }
- /missing.txt -> 404 text/plain; charset=utf-8
- 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 起)就能提供靜態網站