package site import ( "crypto/sha256" "embed" "encoding/hex" "html/template" "io/fs" "os" "path" "path/filepath" "strings" "sync" "github.com/luciochen233/luphoto/internal/fsutil" ) //go:embed static var staticFiles embed.FS type Asset struct { Name string URL string data []byte } type Assets struct { JS Asset CSS Asset Worker Asset Favicon Asset Fonts []Asset Chop template.HTML } var loadAssets = sync.OnceValue(func() Assets { assets := Assets{ JS: hashedAsset("static/app.js"), CSS: hashedAsset("static/app.css"), Worker: hashedAsset("static/worker.js"), Favicon: hashedAsset("static/favicon.svg"), Chop: template.HTML(strings.TrimSpace(string(mustRead("static/lucio-chop-chen.svg")))), } entries, err := fs.ReadDir(staticFiles, "static") if err != nil { panic(err) } for _, entry := range entries { name := entry.Name() if path.Ext(name) != ".woff2" { continue } font := Asset{Name: name, URL: "/assets/" + name, data: mustRead("static/" + name)} assets.Fonts = append(assets.Fonts, font) } return assets }) func mustRead(source string) []byte { data, err := staticFiles.ReadFile(source) if err != nil { panic(err) } return data } func hashedAsset(source string) Asset { data := mustRead(source) sum := sha256.Sum256(data) base := path.Base(source) ext := path.Ext(base) name := strings.TrimSuffix(base, ext) + "." + hex.EncodeToString(sum[:])[:8] + ext return Asset{Name: name, URL: "/assets/" + name, data: data} } func StaticAssets() Assets { return loadAssets() } func (a Assets) Write(buildDir string) error { dir := filepath.Join(buildDir, "assets") if err := os.MkdirAll(dir, 0o755); err != nil { return err } files := append([]Asset{a.JS, a.CSS, a.Worker, a.Favicon}, a.Fonts...) errs := make(chan error, len(files)) var wg sync.WaitGroup for _, asset := range files { wg.Add(1) go func(asset Asset) { defer wg.Done() target := filepath.Join(dir, asset.Name) if path.Ext(asset.Name) == ".woff2" { errs <- fsutil.WriteFileAtomic(target, asset.data, 0o644) return } errs <- fsutil.WritePublicAtomic(target, asset.data) }(asset) } wg.Wait() close(errs) for err := range errs { if err != nil { return err } } return nil }