104 lines
2.5 KiB
Go
104 lines
2.5 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"io/fs"
|
|
"mime"
|
|
"net/http"
|
|
"path"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// BuildID is injected by Docker/Debian build scripts. It deliberately changes
|
|
// at build time, even when the public package version stays at 0.1.1.
|
|
// In regular `go test` / `go build` content hashes still identify every asset.
|
|
var BuildID = "development"
|
|
|
|
type staticAsset struct {
|
|
data []byte
|
|
mime string
|
|
etag string
|
|
}
|
|
|
|
var staticOnce sync.Once
|
|
var staticURLs map[string]string
|
|
var staticRoutes map[string]staticAsset
|
|
var staticErr error
|
|
|
|
func makeStaticManifest() {
|
|
staticURLs = make(map[string]string)
|
|
staticRoutes = make(map[string]staticAsset)
|
|
files, err := fs.Sub(assets, "web/static")
|
|
if err != nil {
|
|
staticErr = err
|
|
return
|
|
}
|
|
err = fs.WalkDir(files, ".", func(filename string, entry fs.DirEntry, walkErr error) error {
|
|
if walkErr != nil {
|
|
return walkErr
|
|
}
|
|
if entry.IsDir() {
|
|
return nil
|
|
}
|
|
raw, err := fs.ReadFile(files, filename)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
digest := sha256.Sum256(append([]byte(BuildID+"\x00"), raw...))
|
|
stamp := hex.EncodeToString(digest[:])[:16]
|
|
ext := path.Ext(filename)
|
|
hashed := strings.TrimSuffix(filename, ext) + "." + stamp + ext
|
|
url := "/static/" + hashed
|
|
kind := mime.TypeByExtension(ext)
|
|
switch ext {
|
|
case ".css":
|
|
kind = "text/css; charset=utf-8"
|
|
case ".js":
|
|
kind = "text/javascript; charset=utf-8"
|
|
case ".svg":
|
|
kind = "image/svg+xml"
|
|
}
|
|
if kind == "" {
|
|
kind = "application/octet-stream"
|
|
}
|
|
staticURLs[filename] = url
|
|
staticRoutes["/"+hashed] = staticAsset{data: raw, mime: kind, etag: `"` + stamp + `"`}
|
|
return nil
|
|
})
|
|
staticErr = err
|
|
}
|
|
|
|
func assetURL(name string) string {
|
|
staticOnce.Do(makeStaticManifest)
|
|
if staticErr != nil {
|
|
panic(fmt.Errorf("prepare static assets: %w", staticErr))
|
|
}
|
|
if url, ok := staticURLs[name]; ok {
|
|
return url
|
|
}
|
|
panic("unknown embedded static asset: " + name)
|
|
}
|
|
|
|
func staticHandler() http.Handler {
|
|
staticOnce.Do(makeStaticManifest)
|
|
if staticErr != nil {
|
|
panic(staticErr)
|
|
}
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
asset, ok := staticRoutes["/"+strings.TrimPrefix(r.URL.Path, "/")]
|
|
if !ok {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", asset.mime)
|
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
|
w.Header().Set("ETag", asset.etag)
|
|
http.ServeContent(w, r, path.Base(r.URL.Path), time.Time{}, bytes.NewReader(asset.data))
|
|
})
|
|
}
|