在 Go 中,可以通过 embed 包将 HTML 和静态文件打包到可执行文件中,从而简化部署流程。embed 是 Go 1.16 引入的官方功能,用于将静态文件嵌入到二进制文件中。
创建目录结构
将 HTML 和静态文件放入指定目录,例如:
|- main.go
|- web/
|- index.html
|- assets/
|- style.css
|- script.js
编写代码
使用 embed 包嵌入文件
package main
import (
"embed"
"fmt"
"net/http"
)
//go:embed web/index.html
var indexHTML embed.FS
//go:embed web/assets/*
var assets embed.FS
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
content, _ := indexHTML.ReadFile("web/index.html")
w.Write(content)
})
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.FS(assets))))
fmt.Println("Server running at http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
评论区