Files
my_website/internal/api/project_handler.go
2025-11-11 20:55:18 +07:00

56 lines
1.3 KiB
Go

package api
import (
"database/sql"
"duhweb/internal/store"
"fmt"
"html/template"
"net/http"
)
type ProjectHandler struct {
Templates *template.Template
ProjectStore *store.SQLiteProjectStore
}
func (h *ProjectHandler) Render(w http.ResponseWriter, tmpl string, data interface{}) {
if err := h.Templates.ExecuteTemplate(w, tmpl, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func NewProjectHandler(db *sql.DB) *ProjectHandler {
tmpl := template.Must(template.New("").ParseGlob("views/*.html"))
template.Must(tmpl.ParseGlob("views/partials/*.html"))
return &ProjectHandler{
Templates: tmpl,
ProjectStore: store.NewSQLiteProjectStore(db),
}
}
func (h *ProjectHandler) InitPage(w http.ResponseWriter, r *http.Request) {
var hxRequest = r.Header.Get("HX-Request")
if hxRequest != "true" {
h.Render(w, "index", nil)
return
}
h.Render(w, "about-partial", nil)
}
func (h *ProjectHandler) ProjectsPage(w http.ResponseWriter, r *http.Request) {
var hxRequest = r.Header.Get("HX-Request")
fmt.Println(hxRequest)
projects, err := h.ProjectStore.GetAllProjects()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if hxRequest != "true" {
h.Render(w, "projects", projects)
return
}
h.Render(w, "projects-partial", projects)
}