# 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"`（見[套件與匯入](/modules-packages-imports)）

`embed` 套件的 API 細節見 [embed](/pkg-embed)。

### 嵌入成 string

最簡單的用法：把一個文字檔讀成字串。下面把 `version.txt` 嵌入，執行時不再需要這個檔案。

檔案樹：

```text
embedstr/
├── go.mod
├── main.go
└── version.txt
```

`version.txt`（內容是一行 `v1.4.2`，結尾有換行）：

```text
v1.4.2
```

`main.go`：

```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))
}
```

執行：

```text
$ go run .
```

輸出：

```text
"v1.4.2\n"
version: v1.4.2
```

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

### 嵌入成 []byte

需要把內容交給 `json.Unmarshal` 這類吃 `[]byte` 的函式，或是圖片等二進位檔時，用 `[]byte` 比較方便。下面嵌入預設設定檔並解析（JSON 用法見 [JSON](/composite-json)）。

檔案樹：

```text
embedbytes/
├── go.mod
├── config.json
└── main.go
```

`config.json`：

```text
{"port": 8080, "debug": true}
```

`main.go`：

```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)
}
```

執行：

```text
$ go run .
```

輸出：

```text
bytes: 30
{Port:8080 Debug:true}
```

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

### embed.FS 嵌入多個檔案

要嵌入一整個目錄或多個檔案時，用 `embed.FS`。它是一個唯讀的虛擬檔案系統，實作了 `io/fs` 的 `fs.FS` 介面（見 [io/fs](/pkg-io-fs)），所以能交給所有接受 `fs.FS` 的函式，例如 `fs.WalkDir`、`template.ParseFS`。

一行 `//go:embed` 可以寫多個路徑（用空白分隔），也可以使用 `*` 這類萬用字元。

| 方法 | 作用 |
| --- | --- |
| `ReadFile(name)` | 讀取單一檔案的完整內容 |
| `ReadDir(name)` | 列出目錄內容 |
| `Open(name)` | 開啟檔案，回傳 `fs.File` |

檔案樹：

```text
embedfs/
├── go.mod
├── main.go
├── notes.txt
└── templates/
    ├── .draft.tmpl
    ├── bye.tmpl
    ├── hello.tmpl
    └── mail/
        └── welcome.tmpl
```

`templates/hello.tmpl`：

```text
Hello, {{.}}!
```

`templates/bye.tmpl`：

```text
Bye, {{.}}.
```

`templates/mail/welcome.tmpl`：

```text
Welcome mail for {{.}}
```

`templates/.draft.tmpl` 內容為 `secret`，`notes.txt` 內容為 `notes`（各一行）。

`main.go`：

```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")
}
```

執行：

```text
$ go run .
```

輸出：

```text
. 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/*` | 萬用字元直接比對到的檔案全部包含（但更深層子目錄裡的仍會略過） |

檔案樹：

```text
embedall/
├── go.mod
├── main.go
└── templates/
    ├── .draft.tmpl
    ├── _wip.tmpl
    └── hello.tmpl
```

`main.go`：

```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)
}
```

執行：

```text
$ go run .
```

輸出：

```text
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` 的錯誤都在編譯時就會被抓出來。路徑比對不到任何檔案時：

```text
main.go:8:12: pattern missing.txt: no matching files found
```

把 `//go:embed` 寫在函式裡的區域變數上時：

```text
./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](/pkg-net-http)）。

簽名：

```go
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](/pkg-net-http-httptest)）來發送請求。

檔案樹：

```text
embedweb/
├── go.mod
├── main.go
└── static/
    ├── index.html
    └── css/
        └── site.css
```

`static/index.html`：

```text
<h1>Hello embed</h1>
```

`static/css/site.css`：

```text
h1 { color: teal; }
```

`main.go`：

```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)
	}
}
```

執行：

```text
$ go run .
```

輸出：

```text
/ -> 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 起）就能提供靜態網站

## 資料來源

- [gopl-zh/gopl-zh.github.com（《Go 語言聖經》中譯本，章節架構參考）](https://github.com/gopl-zh/gopl-zh.github.com)
- [The Go Programming Language Specification](https://go.dev/ref/spec)
- [Go 官方文件](https://go.dev/doc/)
- [Go 官方部落格](https://go.dev/blog/)
