readysite / example / controllers / home.go
2.2 KB
home.go
package controllers

import (
	"fmt"
	"net/http"
	"time"

	"github.com/readysite/readysite/example/models"
	"github.com/readysite/readysite/pkg/application"
)

// HomeController handles the homepage and API routes.
type HomeController struct {
	application.BaseController
}

// Home returns the controller name and instance.
func Home() (string, *HomeController) {
	return "home", &HomeController{}
}

// Setup registers routes.
func (c *HomeController) Setup(app *application.App) {
	c.BaseController.Setup(app)
	http.Handle("GET /", app.Serve("index.html", nil))
	http.Handle("GET /about", app.Serve("about.html", nil))
	http.Handle("GET /api/click", app.Method(c, "Click", nil))
	http.Handle("GET /api/time", app.Method(c, "Time", nil))
	http.Handle("GET /api/live", app.Method(c, "Live", nil))
}

// Handle returns a request-scoped controller instance.
func (c HomeController) Handle(r *http.Request) application.Controller {
	c.Request = r
	return &c
}

// Message returns the greeting message (accessible in templates as {{home.Message}}).
func (c *HomeController) Message() string {
	return "Hello, ReadySite!"
}

// Posts returns all posts (accessible in templates as {{home.Posts}}).
func (c *HomeController) Posts() []*models.Post {
	posts, _ := models.Posts.All()
	return posts
}

// Click handles the HTMX button click.
func (c *HomeController) Click(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")
	fmt.Fprintf(w, `<div class="alert alert-success">Button clicked at %s</div>`, time.Now().Format("15:04:05"))
}

// Time returns the current server time.
func (c *HomeController) Time(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")
	fmt.Fprint(w, time.Now().Format("15:04:05"))
}

// CounterProps returns props for the Counter component.
func (c *HomeController) CounterProps() map[string]any {
	return map[string]any{
		"initial": 0,
		"label":   "Clicks",
	}
}

// Live streams server time via SSE for HTMX.
func (c *HomeController) Live(w http.ResponseWriter, r *http.Request) {
	stream := c.Stream(w)

	for {
		select {
		case <-r.Context().Done():
			return
		case <-time.After(time.Second):
			stream.Render("time", "live-time.html", time.Now().Format("15:04:05"))
		}
	}
}
← Back