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.
This commit is contained in:
79
backend/libs/web/renderer.go
Normal file
79
backend/libs/web/renderer.go
Normal file
@@ -0,0 +1,79 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user