readysite / pkg / frontend / controller.go
1.4 KB
controller.go
package frontend

import (
	"log"
	"net/http"

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

func (f *Frontend) Controller() (string, *Controller) {
	return "frontend", &Controller{frontend: f}
}

// Controller is the frontend controller that handles component bundling and serving.
type Controller struct {
	frontend *Frontend
}

// Setup is called when the controller is registered with the application.
// It builds the components and registers routes.
func (c *Controller) Setup(app *application.App) {
	// Build components
	if err := c.frontend.Build(); err != nil {
		if !c.frontend.DevMode {
			// In production, fail loudly so broken JavaScript is caught early
			log.Fatalf("[frontend] Build failed: %v", err)
		}
		log.Printf("[frontend] Build error: %v", err)
	}

	// Start file watcher for HMR in dev mode
	if c.frontend.DevMode {
		if err := c.frontend.Dev(); err != nil {
			log.Printf("[frontend] Dev server error: %v", err)
		}
	}

	// Register routes
	http.HandleFunc("GET /_frontend/hmr", c.frontend.handleHMR)
	http.HandleFunc("GET /_frontend/components.js", c.frontend.handleComponents)
	http.HandleFunc("GET /_frontend/components.js.map", c.frontend.handleSourceMap)

	// Register template functions
	app.Func("frontend_script", c.frontend.Script)
	app.Func("render", c.frontend.Render)
}

// Handle implements the Controller interface (required but not used for frontend).
func (c *Controller) Handle(r *http.Request) application.Controller {
	return c
}
← Back