grain/app/app.go

77 lines
1.6 KiB
Go
Raw Normal View History

package app
2024-07-23 20:40:39 +00:00
import (
2024-07-31 18:41:48 +00:00
"grain/server/db"
relay "grain/server/types"
2024-07-23 20:40:39 +00:00
"html/template"
"net/http"
)
type PageData struct {
Title string
Theme string
Events []relay.Event
}
2024-07-23 20:40:39 +00:00
func RootHandler(w http.ResponseWriter, r *http.Request) {
// Fetch the top ten most recent events
client := db.GetClient()
events, err := FetchTopTenRecentEvents(client)
if err != nil {
http.Error(w, "Unable to fetch events", http.StatusInternalServerError)
return
}
2024-07-23 20:40:39 +00:00
data := PageData{
Title: "GRAIN Relay",
Events: events,
2024-07-23 20:40:39 +00:00
}
2024-07-23 20:40:39 +00:00
RenderTemplate(w, data, "index.html")
}
// Define the base directories for views and templates
const (
2024-07-31 19:54:42 +00:00
viewsDir = "app/views/"
templatesDir = "app/views/templates/"
2024-07-23 20:40:39 +00:00
)
// Define the common layout templates filenames
var templateFiles = []string{
2024-07-27 20:46:25 +00:00
"layout.html",
2024-07-23 20:40:39 +00:00
"header.html",
"footer.html",
}
// Initialize the common templates with full paths
var layout = PrependDir(templatesDir, templateFiles)
func RenderTemplate(w http.ResponseWriter, data PageData, view string) {
// Append the specific template for the route
templates := append(layout, viewsDir+view)
// Parse all templates
tmpl, err := template.ParseFiles(templates...)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Execute the "layout" template
err = tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// Helper function to prepend a directory path to a list of filenames
func PrependDir(dir string, files []string) []string {
var fullPaths []string
for _, file := range files {
fullPaths = append(fullPaths, dir+file)
}
return fullPaths
}
2024-07-28 13:41:10 +00:00