Files
warpbox-dev/backend/libs/web/renderer.go
Daniel Legt 9b8ef16474 feat: initialize warpbox.dev project structure and backend
Initialize the repository with the core Go backend architecture and a frontend mockup for warpbox.dev, a self-hosted file-sharing application.

- Set up Go backend modules for configuration, HTTP server, middleware, handlers, and templates.
- Add local development scripts, environment templates, and basic project configuration.
- Include a React-based frontend mockup under the docs directory.
2026-05-25 15:36:49 +03:00

80 lines
1.7 KiB
Go

package web
import (
"html/template"
"net/http"
"path/filepath"
"time"
)
type Renderer struct {
templates map[string]*template.Template
appName string
baseURL string
}
type PageData struct {
AppName string
BaseURL string
Title string
Description string
CurrentYear int
Data any
}
func NewRenderer(templateDir, appName, baseURL string) (*Renderer, error) {
layouts, err := filepath.Glob(filepath.Join(templateDir, "layouts", "*.gohtml"))
if err != nil {
return nil, err
}
partials, err := filepath.Glob(filepath.Join(templateDir, "partials", "*.gohtml"))
if err != nil {
return nil, err
}
pages, err := filepath.Glob(filepath.Join(templateDir, "pages", "*.gohtml"))
if err != nil {
return nil, err
}
templates := make(map[string]*template.Template, len(pages))
for _, page := range pages {
files := append([]string{}, layouts...)
files = append(files, partials...)
files = append(files, page)
parsed, err := template.ParseFiles(files...)
if err != nil {
return nil, err
}
templates[filepath.Base(page)] = parsed
}
return &Renderer{
templates: templates,
appName: appName,
baseURL: baseURL,
}, nil
}
func (r *Renderer) Render(w http.ResponseWriter, status int, page string, data PageData) {
data.AppName = r.appName
data.BaseURL = r.baseURL
data.CurrentYear = time.Now().Year()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
tmpl, ok := r.templates[page]
if !ok {
http.Error(w, "template not found", http.StatusInternalServerError)
return
}
if err := tmpl.ExecuteTemplate(w, page, data); err != nil {
http.Error(w, "template render error", http.StatusInternalServerError)
}
}