使用embed功能,他是Go 1.16+ 的新增功能静态文件内嵌到二进制文件中。例如
将 templates/ 目录下的 .html 文件和 static/style.css 内嵌进二进制,并启动一个 HTTP 服务器,访问根路径即可看到 index.html 页面。
完整代码:main.go
package main
import (
"embed"
"fmt"
"net/http"
)
//go:embed templates/*.html static/*
var content embed.FS
func main() {
// 可选:打印 index.html 内容到控制台(调试用)
if data, err := content.ReadFile("templates/index.html"); err == nil {
fmt.Println("Loaded index.html:")
fmt.Println(string(data))
}
// 启动 HTTP 服务器,直接托管内嵌的静态资源
http.Handle("/", http.FileServer(http.FS(content)))
fmt.Println("Server starting on http://localhost:8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
} 所需目录结构(和 main.go 同级):
your-project/
├── main.go
├── templates/
│ └── index.html
└── static/
└── style.css 你不需要真的有 static/ 下的其他文件——static/* 会自动包含该目录下所有文件。
示例 templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Embedded App</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<h1>Hello from embedded HTML!</h1>
<p>This page is served from Go binary with no external files.</p>
</body>
</html> 示例 static/style.css:
body {
font-family: Arial, sans-serif;
background: #f0f0f0;
text-align: center;
padding: 50px;
}
h1 {
color: #333;
} 如何运行?
确保你使用 Go 1.16 或更高版本(推荐 1.20+):
go version
在项目根目录执行:
go run main.go
打开浏览器访问:http://localhost:8080→ 你会看到带样式的网页,所有资源都来自二进制内部!
(可选)编译成独立二进制:
go build -o myapp main.go ./myapp
然后你可以把这个 myapp 文件复制到任何地方运行——无需附带 templates/ 或 static/ 目录!
注意事项
路径区分大小写(Linux/macOS 严格,Windows 较宽松但建议统一小写)。
http.FS(content) 要求路径以 / 开头,所以 HTML 中引用 CSS 要写成 /static/style.css。
如果你只想要 API 而不是文件服务器,可以把 http.FileServer 换成你自己的 handler。
网友回复


