package static import ( "embed" "io/fs" "net/http" "sync" ) //go:embed static var staticFS embed.FS var ( indexHTML []byte once sync.Once ) // GetIndex 返回入口页。 // // index.html 缺失时回退到 placeholder.html:前端产物不进版本库, // 新克隆里只有占位页。回退而不是报错是故意的 —— // 只改后端的人应当能直接 go run 起来调 API,而不必先装 node。 func GetIndex() []byte { once.Do(func() { if data, err := fs.ReadFile(staticFS, "static/index.html"); err == nil { indexHTML = data return } indexHTML, _ = fs.ReadFile(staticFS, "static/placeholder.html") }) return indexHTML } func Handler() http.Handler { sub, _ := fs.Sub(staticFS, "static") return http.FileServer(http.FS(sub)) } // ReadFile 读打包进来的静态文件(目前只给 manifest 用)。 // // 用 embed 而不是读磁盘:静态根可由 --static 指定成别的目录, // 那时 manifest 会跟着一起"消失";它属于前端产物的一部分,必须和应用同源同版本。 func ReadFile(name string) ([]byte, error) { return fs.ReadFile(staticFS, "static/"+name) }