staticspa.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. // Package staticspa — estáticos + SPA fallback (paridad app.js:44-60).
  2. //
  3. // - Sirve ficheros existentes del root (STATIC_DIR del env si se define;
  4. // si no, el dist EMBEBIDO — ver abajo).
  5. // - index.html se cachea en memoria al arranque; si falta → warning y el
  6. // fallback devuelve 503 texto.
  7. // - Fallback GET: /api/* → 404 JSON {error:'not_found'}; /assets/* → 404
  8. // plano; resto → 200 HTML con el index.html cacheado (SPA fallback).
  9. //
  10. // EMBED: go:embed no puede referenciar ../../app/dist (fuera del módulo), así
  11. // que el binario embebe internal/staticspa/dist. CI debe copiar app/dist a
  12. // server-go/internal/staticspa/dist antes de `go build` (hasta entonces hay
  13. // un index.html placeholder). STATIC_DIR siempre tiene prioridad sobre el
  14. // embed (override para desarrollo/despliegue clásico).
  15. package staticspa
  16. import (
  17. "embed"
  18. "io"
  19. "io/fs"
  20. "log"
  21. "net/http"
  22. "os"
  23. "path"
  24. "strings"
  25. )
  26. //go:embed dist
  27. var embeddedDist embed.FS
  28. // Handler sirve los estáticos y el SPA fallback.
  29. type Handler struct {
  30. files fs.FS
  31. indexHTML []byte // nil si no hay index.html
  32. }
  33. // New crea el handler. Si staticDir != "" sirve ese directorio del disco
  34. // (override STATIC_DIR); si no, usa el dist embebido en el binario.
  35. // Lee index.html en memoria al arranque (warning si falta, como app.js:51).
  36. func New(staticDir string) *Handler {
  37. h := &Handler{}
  38. desc := staticDir
  39. if staticDir != "" {
  40. h.files = os.DirFS(staticDir)
  41. } else {
  42. sub, err := fs.Sub(embeddedDist, "dist")
  43. if err != nil {
  44. sub = embeddedDist
  45. }
  46. h.files = sub
  47. desc = "(embed)"
  48. }
  49. if data, err := fs.ReadFile(h.files, "index.html"); err == nil {
  50. h.indexHTML = data
  51. } else {
  52. log.Printf("[netpulse] STATIC_DIR=%s has no index.html (missing \"npm run build\" in app/?)", desc)
  53. }
  54. return h
  55. }
  56. // LocalesFS expone el FS con los catálogos de idioma del dist
  57. // ("<lang>/translation.json"), embebidos en el binario. Lo usa el paquete
  58. // alertlang para traducir las notificaciones push server-side (#888/#889).
  59. func LocalesFS() fs.FS {
  60. sub, err := fs.Sub(embeddedDist, "dist/locales")
  61. if err != nil {
  62. return embeddedDist
  63. }
  64. return sub
  65. }
  66. // serveFile sirve el fichero `name` si existe y no es directorio.
  67. func (h *Handler) serveFile(w http.ResponseWriter, r *http.Request, name string) bool {
  68. if !fs.ValidPath(name) {
  69. return false
  70. }
  71. f, err := h.files.Open(name)
  72. if err != nil {
  73. return false
  74. }
  75. defer f.Close()
  76. st, err := f.Stat()
  77. if err != nil || st.IsDir() {
  78. return false
  79. }
  80. rs, ok := f.(io.ReadSeeker)
  81. if !ok {
  82. return false
  83. }
  84. http.ServeContent(w, r, st.Name(), st.ModTime(), rs)
  85. return true
  86. }
  87. // notFoundPlain replica el 404 por defecto de Hono (c.notFound()): cuerpo de
  88. // texto "404 Not Found", no el "404 page not found\n" de net/http.
  89. func notFoundPlain(w http.ResponseWriter) {
  90. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  91. w.WriteHeader(http.StatusNotFound)
  92. _, _ = w.Write([]byte("404 Not Found"))
  93. }
  94. // ServeHTTP implementa http.Handler: estático si existe; si no, fallback.
  95. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  96. p := r.URL.Path
  97. // /api/* nunca llega aquí (el mux lo enruta antes), pero por seguridad:
  98. if strings.HasPrefix(p, "/api/") {
  99. w.Header().Set("Content-Type", "application/json")
  100. w.WriteHeader(http.StatusNotFound)
  101. _, _ = w.Write([]byte(`{"error":"not_found"}`))
  102. return
  103. }
  104. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  105. notFoundPlain(w)
  106. return
  107. }
  108. // Estático: sirve el fichero si existe (raíz → index.html).
  109. name := strings.TrimPrefix(path.Clean("/"+p), "/")
  110. if name == "" {
  111. name = "index.html"
  112. }
  113. // Cache por tipo de recurso (fix pantalla negra tras update):
  114. // - /assets/* tiene hash de contenido → inmutable 1 año.
  115. // - index.html y sw.js SIN no-cache se servían desde la caché del
  116. // navegador apuntando a hashes que el update acababa de borrar →
  117. // los JS no cargaban y #root quedaba vacío (pantalla negra hasta
  118. // refrescar a mano). no-cache obliga a revalidar cada navegación.
  119. if strings.HasPrefix(p, "/assets/") {
  120. w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
  121. } else if name == "index.html" || name == "sw.js" {
  122. w.Header().Set("Cache-Control", "no-cache")
  123. }
  124. if h.serveFile(w, r, name) {
  125. return
  126. }
  127. if h.serveFile(w, r, path.Join(name, "index.html")) {
  128. return
  129. }
  130. // Fallback (GET *):
  131. if strings.HasPrefix(p, "/assets/") {
  132. notFoundPlain(w) // 404 plano, sin JSON (cuerpo "404 Not Found" como Hono)
  133. return
  134. }
  135. if h.indexHTML == nil {
  136. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  137. w.WriteHeader(http.StatusServiceUnavailable)
  138. _, _ = w.Write([]byte("NetPulse: frontend no compilado (cd app && npm run build)"))
  139. return
  140. }
  141. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  142. w.WriteHeader(http.StatusOK)
  143. _, _ = w.Write(h.indexHTML)
  144. }