69aa98e18c
- internal/config: конфигурация из env с валидацией и дефолтами (§5.1, §9.1) - internal/httpx: middleware (request id, slog-логи, recover, security-заголовки), единый формат ошибок §8.5 и лимит тела запроса - internal/database: SQLite WAL + busy_timeout + foreign_keys, один writer и пул чтения, goose-миграции embedded, PRAGMA optimize по расписанию - internal/meta: полезная нагрузка /api/v1/meta (версия, фичи, лимиты) - internal/server: маршруты, SPA-раздача собранного клиента, OpenAPI 3.1 - cmd/glchat: точка входа с graceful shutdown и JSON-логами - тесты: конфиг, миграции и идемпотентность, HTTP-эндпоинты, статика, 404/405
69 lines
1.8 KiB
Go
69 lines
1.8 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"io/fs"
|
|
"mime"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
// staticHandler serves the built web client with SPA fallback: unknown paths
|
|
// return index.html so client-side routes survive a page reload.
|
|
type staticHandler struct {
|
|
root string
|
|
}
|
|
|
|
func newStaticHandler(root string) *staticHandler {
|
|
return &staticHandler{root: root}
|
|
}
|
|
|
|
func (h *staticHandler) serve(w http.ResponseWriter, r *http.Request) {
|
|
cleaned := path.Clean("/" + r.URL.Path)
|
|
rel := strings.TrimPrefix(cleaned, "/")
|
|
if rel == "" {
|
|
h.serveIndex(w, r)
|
|
return
|
|
}
|
|
|
|
info, err := fs.Stat(os.DirFS(h.root), rel)
|
|
if err != nil || info.IsDir() {
|
|
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
|
http.Error(w, "internal error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
h.serveIndex(w, r)
|
|
return
|
|
}
|
|
|
|
if contentType := mime.TypeByExtension(filepath.Ext(rel)); contentType != "" {
|
|
w.Header().Set("Content-Type", contentType)
|
|
}
|
|
if strings.HasPrefix(rel, "assets/") {
|
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
|
} else {
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
}
|
|
http.ServeFile(w, r, filepath.Join(h.root, filepath.FromSlash(rel)))
|
|
}
|
|
|
|
func (h *staticHandler) serveIndex(w http.ResponseWriter, r *http.Request) {
|
|
index := filepath.Join(h.root, "index.html")
|
|
if _, err := os.Stat(index); err != nil {
|
|
writeClientNotBuilt(w)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
http.ServeFile(w, r, index)
|
|
}
|
|
|
|
func writeClientNotBuilt(w http.ResponseWriter) {
|
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
_, _ = w.Write([]byte("glchat: web client bundle is not present in this image\n"))
|
|
}
|