Files
LuPhoto/internal/site/assets.go
T
2026-11-04 04:22:20 -08:00

67 lines
1.3 KiB
Go

package site
import (
"crypto/sha256"
"embed"
"encoding/hex"
"os"
"path"
"path/filepath"
"strings"
"sync"
"github.com/luciochen233/luphoto/internal/fsutil"
)
//go:embed static/app.js static/app.css static/worker.js
var staticFiles embed.FS
type Asset struct {
Name string
URL string
data []byte
}
type Assets struct {
JS Asset
CSS Asset
Worker Asset
}
var loadAssets = sync.OnceValue(func() Assets {
return Assets{
JS: hashedAsset("static/app.js"),
CSS: hashedAsset("static/app.css"),
Worker: hashedAsset("static/worker.js"),
}
})
func hashedAsset(source string) Asset {
data, err := staticFiles.ReadFile(source)
if err != nil {
panic(err)
}
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
}
for _, asset := range []Asset{a.JS, a.CSS, a.Worker} {
if err := fsutil.WriteFileAtomic(filepath.Join(dir, asset.Name), asset.data, 0o644); err != nil {
return err
}
}
return nil
}