feat(registry): random_hex_id_go_core + spa_handler_go_infra
Dos primitivas reutilizables para apps web del registry: - random_hex_id_go_core: IDs hex aleatorios (apps con SQLite + IDs string) - spa_handler_go_infra: http.Handler que sirve embed.FS con fallback a index.html (patron SPA para React Router/dnd-kit) Ambas creadas via fn-constructor durante apps/kanban (issue 0053). Tests pasan, fn index OK. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package infra
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SPAHandler retorna un http.Handler que sirve los archivos estáticos de fsys
|
||||
// y hace fallback a indexFile para cualquier ruta que no corresponda a un
|
||||
// archivo existente — patrón SPA para React Router y similares.
|
||||
//
|
||||
// fsys es típicamente un iofs.Sub(embed.FS, "frontend/dist").
|
||||
// indexFile es la ruta dentro de fsys del HTML de fallback (ej. "index.html").
|
||||
func SPAHandler(fsys fs.FS, indexFile string) http.Handler {
|
||||
fileServer := http.FileServer(http.FS(fsys))
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Defensa contra path traversal
|
||||
if strings.Contains(r.URL.Path, "..") {
|
||||
http.Error(w, "invalid path", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Normalizar: quitar la barra inicial para fs.Stat
|
||||
path := strings.TrimPrefix(r.URL.Path, "/")
|
||||
if path == "" {
|
||||
path = "."
|
||||
}
|
||||
|
||||
info, err := fs.Stat(fsys, path)
|
||||
if err == nil && !info.IsDir() {
|
||||
// El archivo existe y no es directorio: servir normalmente
|
||||
fileServer.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Fallback a indexFile (ruta no encontrada o directorio)
|
||||
data, err := fs.ReadFile(fsys, indexFile)
|
||||
if err != nil {
|
||||
http.Error(w, "could not read index file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(data) //nolint:errcheck
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
name: spa_handler
|
||||
kind: function
|
||||
lang: go
|
||||
domain: infra
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "func SPAHandler(fsys fs.FS, indexFile string) http.Handler"
|
||||
description: "Retorna un http.Handler que sirve los archivos estaticos de un fs.FS y hace fallback a indexFile cuando el path no existe — patron SPA para React Router y similares."
|
||||
tags: [http, spa, frontend, embed, fileserver]
|
||||
uses_functions: []
|
||||
uses_types: []
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: [io/fs, net/http, strings]
|
||||
params:
|
||||
- name: fsys
|
||||
desc: "fs.FS (tipico iofs.Sub de embed.FS) que contiene los archivos estaticos de la SPA"
|
||||
- name: indexFile
|
||||
desc: "ruta dentro de fsys del HTML de fallback (ej. \"index.html\")"
|
||||
output: "http.Handler que sirve archivos de fsys y hace fallback a indexFile cuando el path no existe — patron SPA para React Router"
|
||||
tested: true
|
||||
tests:
|
||||
- "sirve archivo estatico existente con status 200"
|
||||
- "ruta inexistente hace fallback a index.html con Content-Type text/html"
|
||||
- "raiz retorna index.html"
|
||||
- "path con .. retorna 400"
|
||||
test_file_path: "functions/infra/spa_handler_test.go"
|
||||
file_path: "functions/infra/spa_handler.go"
|
||||
---
|
||||
|
||||
## Ejemplo
|
||||
|
||||
```go
|
||||
//go:embed all:frontend/dist
|
||||
var staticFiles embed.FS
|
||||
|
||||
func main() {
|
||||
sub, _ := iofs.Sub(staticFiles, "frontend/dist")
|
||||
spa := SPAHandler(sub, "index.html")
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/api/", apiRouter())
|
||||
mux.Handle("/", spa)
|
||||
|
||||
http.ListenAndServe(":8080", mux)
|
||||
}
|
||||
```
|
||||
|
||||
## Notas
|
||||
|
||||
Funcion pura — construye el handler a partir de los parametros sin I/O. El handler resultante tiene los siguientes comportamientos:
|
||||
|
||||
1. Si el path contiene `..`, responde 400 (defensa contra path traversal).
|
||||
2. Si el path normalizado corresponde a un archivo real en `fsys` (no directorio), lo sirve con `http.FileServer`.
|
||||
3. En cualquier otro caso (ruta no existe o es directorio), sirve `indexFile` con `Content-Type: text/html; charset=utf-8` y status 200.
|
||||
4. Si `indexFile` no puede leerse, responde 500.
|
||||
|
||||
Pensado para apps que usan `//go:embed all:frontend/dist` y React Router (o cualquier router del lado del cliente). Centraliza el patron que de otro modo cada app escribiria inline.
|
||||
@@ -0,0 +1,77 @@
|
||||
package infra
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
)
|
||||
|
||||
func TestSPAHandler(t *testing.T) {
|
||||
mapFS := fstest.MapFS{
|
||||
"index.html": {
|
||||
Data: []byte(`<!doctype html><html><body>SPA</body></html>`),
|
||||
},
|
||||
"assets/app.js": {
|
||||
Data: []byte(`console.log("app")`),
|
||||
},
|
||||
}
|
||||
|
||||
handler := SPAHandler(mapFS, "index.html")
|
||||
|
||||
t.Run("sirve archivo estatico existente con status 200", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/assets/app.js", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
if body != `console.log("app")` {
|
||||
t.Errorf("unexpected body: %q", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ruta inexistente hace fallback a index.html con Content-Type text/html", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/some/route", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
ct := rec.Header().Get("Content-Type")
|
||||
if ct != "text/html; charset=utf-8" {
|
||||
t.Errorf("got Content-Type %q, want %q", ct, "text/html; charset=utf-8")
|
||||
}
|
||||
body := rec.Body.String()
|
||||
if body == "" {
|
||||
t.Error("expected non-empty body (index.html)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("raiz retorna index.html", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
ct := rec.Header().Get("Content-Type")
|
||||
if ct != "text/html; charset=utf-8" {
|
||||
t.Errorf("got Content-Type %q, want %q", ct, "text/html; charset=utf-8")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("path con .. retorna 400", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/foo/../bar", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("got status %d, want %d", rec.Code, http.StatusBadRequest)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user