A standalone container for web_server, shaped like job-tracker: serves /usaco/ with solved problems public and solving/skipped plus edits (status, link, notes) for the site admin. Git is the only store: the server clones adamf/usaco from Gitea, pulls on the push webhook, and commits edits back. CI builds the image only when site/ changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
66 lines
2.0 KiB
Go
66 lines
2.0 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// SPA serves the built Vue app from dir for every GET under base that no API
|
|
// route claimed. It is installed as gin's NoRoute handler rather than as a
|
|
// base+"/*path" route because gin will not let a catch-all sit beside the
|
|
// /api routes at the same level.
|
|
//
|
|
// History-mode routing means a path such as /usaco/p/moocast is a page of the app,
|
|
// not a file, so anything that is not a file in dir gets index.html — except
|
|
// under /api/ and /assets/, where a miss is a real 404: an API typo should
|
|
// not come back as a page of HTML, and neither should a stale asset hash.
|
|
//
|
|
// Caching: Vite fingerprints everything under assets/, so those are cached
|
|
// for a year; index.html is never cached, so a deploy is picked up on the
|
|
// next load.
|
|
func SPA(dir, base string) gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
p := ctx.Request.URL.Path
|
|
if ctx.Request.Method != http.MethodGet && ctx.Request.Method != http.MethodHead {
|
|
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
|
return
|
|
}
|
|
if p == base {
|
|
ctx.Redirect(http.StatusMovedPermanently, base+"/")
|
|
return
|
|
}
|
|
rel, ok := strings.CutPrefix(p, base+"/")
|
|
if !ok || strings.HasPrefix(rel, "api/") {
|
|
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
|
return
|
|
}
|
|
|
|
// path.Clean on a rooted path cannot climb above the root, so the
|
|
// result always stays inside dir.
|
|
rel = strings.TrimPrefix(path.Clean("/"+rel), "/")
|
|
if rel != "" {
|
|
file := filepath.Join(dir, filepath.FromSlash(rel))
|
|
if info, err := os.Stat(file); err == nil && !info.IsDir() {
|
|
if strings.HasPrefix(rel, "assets/") {
|
|
ctx.Header("Cache-Control", "public, max-age=31536000, immutable")
|
|
} else {
|
|
ctx.Header("Cache-Control", "no-cache")
|
|
}
|
|
ctx.File(file)
|
|
return
|
|
}
|
|
if strings.HasPrefix(rel, "assets/") {
|
|
ctx.Status(http.StatusNotFound)
|
|
return
|
|
}
|
|
}
|
|
ctx.Header("Cache-Control", "no-cache")
|
|
ctx.File(filepath.Join(dir, "index.html"))
|
|
}
|
|
}
|