elTesto/controllers/item_controller.go

68 lines
1.9 KiB
Go
Raw Permalink Normal View History

2025-03-26 22:23:02 +00:00
package controllers
import (
"net/http"
"os"
"path/filepath"
"strconv"
"forgejo.sitodosi.com/betology/elTesto/models"
"github.com/flosch/pongo2/v6"
"github.com/gin-gonic/gin"
)
func GetItems(c *gin.Context) {
// Ruta al archivo de plantilla
rootPath, _ := filepath.Abs(".")
templatePath := filepath.Join(rootPath, "templates/index.html")
// Verificar si el archivo existe
if _, err := os.Stat(templatePath); err != nil {
c.String(http.StatusInternalServerError, "Plantilla no encontrada en: "+templatePath)
return
}
// Cargar la plantilla con Pongo2
tpl := pongo2.Must(pongo2.FromFile(templatePath))
out, err := tpl.Execute(pongo2.Context{"items": models.Items})
if err != nil {
c.String(http.StatusInternalServerError, "Error renderizando plantilla: "+err.Error())
return
}
// Establecer el encabezado Content-Type con charset UTF-8
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(http.StatusOK, out)
}
func GetItemByID(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
for _, item := range models.Items {
if item.ID == id {
// Ruta al archivo de plantilla
rootPath, _ := filepath.Abs(".")
templatePath := filepath.Join(rootPath, "templates/item.html")
// Verificar si el archivo existe
if _, err := os.Stat(templatePath); err != nil {
c.String(http.StatusInternalServerError, "Plantilla no encontrada en: "+templatePath)
return
}
// Cargar la plantilla con Pongo2
tpl := pongo2.Must(pongo2.FromFile(templatePath))
out, err := tpl.Execute(pongo2.Context{"item": item})
if err != nil {
c.String(http.StatusInternalServerError, "Error renderizando plantilla: "+err.Error())
return
}
// Establecer el encabezado Content-Type con charset UTF-8
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(http.StatusOK, out)
return
}
}
c.String(http.StatusNotFound, "Item no encontrado")
}