Files
links.stevanfreeborn.com/internal/handlers/main.go
T

90 lines
1.8 KiB
Go
Raw Normal View History

// Package handlers provides HTTP handlers for the web application.
package handlers
import (
2025-11-24 21:34:15 -06:00
"encoding/json"
"io/fs"
2025-11-24 08:58:47 -06:00
"math"
"net/http"
"text/template"
2025-11-24 08:58:47 -06:00
"time"
"github.com/StevanFreeborn/links.stevanfreeborn.com/internal/assets"
)
2025-11-24 21:34:15 -06:00
const LINKS_JSON_PATH = "json/links.json"
2025-11-24 08:58:47 -06:00
const DAYS_IN_YEAR = 365
const HOURS_IN_DAY = 24
var birthday time.Time = time.Date(1993, time.April, 21, 0, 0, 0, 0, time.UTC)
2025-11-24 21:34:15 -06:00
type Link struct {
Href string `json:"href"`
Icon string `json:"icon"`
Text string `json:"text"`
}
2025-11-24 08:58:47 -06:00
type IndexViewModel struct {
2025-11-24 21:34:15 -06:00
Age float64
Links []Link
2025-11-24 08:58:47 -06:00
}
func Index(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFS(assets.Templates, "templates/index.gohtml")
if err != nil {
http.Error(w, "Unable to load template", http.StatusInternalServerError)
return
}
2025-11-24 21:34:15 -06:00
linksFile, err := assets.JSON.Open(LINKS_JSON_PATH)
if err != nil {
http.Error(w, "Unable to load links", http.StatusInternalServerError)
return
}
links, err := readLinksFromJSON(linksFile)
if err != nil {
http.Error(w, "Unable to parse links", http.StatusInternalServerError)
return
}
2025-11-24 08:58:47 -06:00
age := time.Since(birthday).Hours() / HOURS_IN_DAY / DAYS_IN_YEAR
viewModel := IndexViewModel{
2025-11-24 21:34:15 -06:00
Age: math.Floor(age),
Links: links,
2025-11-24 08:58:47 -06:00
}
t.Execute(w, viewModel)
}
func CSS(w http.ResponseWriter, r *http.Request) {
http.ServeFileFS(w, r, assets.CSS, r.URL.Path)
}
2025-11-15 12:35:51 -06:00
func Fonts(w http.ResponseWriter, r *http.Request) {
http.ServeFileFS(w, r, assets.Fonts, r.URL.Path)
}
2025-11-24 21:34:15 -06:00
func Images(w http.ResponseWriter, r *http.Request) {
http.ServeFileFS(w, r, assets.Images, r.URL.Path)
}
func readLinksFromJSON(file fs.File) ([]Link, error) {
defer file.Close()
var links []Link
decoder := json.NewDecoder(file)
err := decoder.Decode(&links)
if err != nil {
return nil, err
}
return links, nil
}