Documentation
¶
Overview ¶
Package runtime provides asset serving integration with Stoic server runtime.
Package runtime provides the server runtime for Stoic applications: router, action dispatcher, middleware, and state management.
Index ¶
- func ActionHandler[In, Out any](action stoic.Action[In, Out], ...) http.HandlerFunc
- func ActionHandlerSimple[In, Out any](action stoic.Action[In, Out], render func(out Out) templ.Component, ...) http.HandlerFunc
- func AssetManifest() *assets.Manifest
- func CSRFMiddleware(next http.Handler) http.Handler
- func DevAddr(fallback string) string
- func LoggerMiddleware(next http.Handler) http.Handler
- func RecoverMiddleware(next http.Handler) http.Handler
- func RequestID(ctx context.Context) string
- func RequestIDMiddleware(next http.Handler) http.Handler
- func SessionMiddleware(next http.Handler) http.Handler
- func TimingMiddleware(next http.Handler) http.Handler
- type AssetOption
- type Middleware
- type Option
- func LoadManifest(manifestPath string) Option
- func WithAssetHandler(h http.Handler) Option
- func WithAssets(opts ...AssetOption) Option
- func WithBasePath(p string) Option
- func WithDefaultErrorHandler(h stoic.ErrorHandler) Option
- func WithDevFSRoot(root string) Option
- func WithDevMode() Option
- func WithErrorHandler(code int, h stoic.ErrorHandler) Option
- func WithLogger(l *slog.Logger) Option
- func WithMiddleware(mw ...Middleware) Option
- type Server
- func (s *Server) HandleError(w http.ResponseWriter, r *http.Request, code int, message string)
- func (s *Server) Handler() http.Handler
- func (s *Server) ListenAndStart(addr string) error
- func (s *Server) MountAll()
- func (s *Server) Mux() *http.ServeMux
- func (s *Server) RegisterAction(info stoic.ActionInfo)
- func (s *Server) RegisterHandler(path string, handler http.Handler)
- func (s *Server) RegisterPage(path string, handler http.HandlerFunc)
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ActionHandler ¶
func ActionHandler[In, Out any]( action stoic.Action[In, Out], render func(ctx context.Context, out Out) templ.Component, decode func(r *http.Request) (In, error), ) http.HandlerFunc
ActionHandler creates a standard http.HandlerFunc for an action. It decodes input, calls the action, and renders the output component. If the action returns a stoic.StatusCodeError, the handler writes the appropriate HTTP status code.
func ActionHandlerSimple ¶
func ActionHandlerSimple[In, Out any]( action stoic.Action[In, Out], render func(out Out) templ.Component, decode func(r *http.Request) (In, error), ) http.HandlerFunc
ActionHandlerSimple is like ActionHandler but for render functions that do not need a context parameter. Use with the // stoic:action render=ComponentName annotation when the render function is a plain templ component constructor.
func AssetManifest ¶
AssetManifest returns the loaded asset manifest or nil. Exposed for debugging/admin purposes.
func CSRFMiddleware ¶
CSRFMiddleware injects and validates CSRF tokens.
func DevAddr ¶
DevAddr returns the address to listen on in development mode. It checks the STOIC_DEV_PORT environment variable first, then falls back.
func LoggerMiddleware ¶
LoggerMiddleware logs incoming requests.
func RecoverMiddleware ¶
RecoverMiddleware recovers from panics and logs them. If a custom 500 error handler is registered, it renders that instead of the plain text "Internal Server Error".
func RequestIDMiddleware ¶
RequestIDMiddleware adds a unique request ID to each request.
func SessionMiddleware ¶
SessionMiddleware ensures a session cookie exists.
Types ¶
type AssetOption ¶
AssetOption configures the asset handler.
func WithAssetPrefix ¶
func WithAssetPrefix(prefix string) AssetOption
WithAssetPrefix changes the asset URL prefix from "/assets/" to the given path. Note: The handler is still registered at "/assets/" in the mux, but assets will expect this prefix in URLs. Use with caution.
type Middleware ¶
Middleware is a function that wraps an http.Handler.
func DefaultMiddleware ¶
func DefaultMiddleware() []Middleware
DefaultMiddleware returns the recommended middleware stack.
type Option ¶
type Option func(*Server)
Option configures the Server.
func LoadManifest ¶
LoadManifest loads the Vite manifest.json and makes it available for template URL resolution.
Example:
srv := runtime.NewServer(
runtime.WithAssets(),
runtime.LoadManifest("manifest.json"),
)
After loading, assets.Script(), assets.Stylesheet() etc. will automatically resolve entry point names to their hashed output paths.
func WithAssetHandler ¶
WithAssetHandler returns a Server Option that registers a pre-configured asset handler. Use this when you need full control over the handler.
func WithAssets ¶
func WithAssets(opts ...AssetOption) Option
WithAssets returns a Server Option that registers the asset handler. It serves embedded static files at /assets/* from the configured FS.
Example usage:
// In your main package:
//go:embed all:dist
var distFS embed.FS
func init() {
assets.SetFS(distFS, "dist")
}
// Create server:
srv := runtime.NewServer(
runtime.WithAssets(),
)
Options can be chained to customize the asset handler:
runtime.WithAssets(runtime.WithAssetPrefix("/static/"))
func WithBasePath ¶
WithBasePath sets the base path for stoic routes (default "/_stoic").
func WithDefaultErrorHandler ¶ added in v0.3.0
func WithDefaultErrorHandler(h stoic.ErrorHandler) Option
WithDefaultErrorHandler sets the fallback error handler for any status code that doesn't have a specific handler registered.
func WithDevFSRoot ¶
WithDevFSRoot sets the filesystem root for development mode. Use with WithDevMode.
func WithDevMode ¶
func WithDevMode() Option
WithDevMode enables development mode (serve from disk). In dev mode, assets are served from DevFSRoot (default: ./frontend/dist) instead of the embedded FS.
func WithErrorHandler ¶ added in v0.3.0
func WithErrorHandler(code int, h stoic.ErrorHandler) Option
WithErrorHandler registers a custom error handler for a specific HTTP status code. The handler returns a templ.Component that the framework renders:
- Full requests get the component wrapped in the layout.
- HTMX partial requests get the bare component.
Unregistered codes fall through to DefaultErrorHandler which renders a simple styled HTML page.
func WithMiddleware ¶
func WithMiddleware(mw ...Middleware) Option
WithMiddleware appends global middleware.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the Stoic HTTP server runtime.
func (*Server) HandleError ¶ added in v0.3.0
HandleError renders an error response through the registered error handler pipeline. Use this in custom page handlers and action handlers to render styled error pages instead of plain http.Error responses.
Example (in a page handler):
srv := runtime.NewServer()
srv.RegisterPage("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
user, err := findUser(r.PathValue("id"))
if err != nil {
srv.HandleError(w, r, http.StatusNotFound, "User not found")
return
}
// render user page...
})
func (*Server) Handler ¶
Handler returns the fully-wrapped http.Handler for the server. Unmatched routes automatically render through the registered error handlers.
func (*Server) ListenAndStart ¶
ListenAndStart starts the server on the given address.
func (*Server) MountAll ¶ added in v0.4.0
func (s *Server) MountAll()
MountAll picks up every component registered via stoic.Register() and wires their actions into this server. Call once after NewServer.
Components self-register in their init() via stoic.Register(). MountAll converts each stoic.ActionEntry into a stoic.ActionInfo and registers it on the server's mux.
func (*Server) RegisterAction ¶
func (s *Server) RegisterAction(info stoic.ActionInfo)
RegisterAction registers an action with the runtime.
func (*Server) RegisterHandler ¶
RegisterHandler registers a generic http.Handler at a path.
func (*Server) RegisterPage ¶
func (s *Server) RegisterPage(path string, handler http.HandlerFunc)
RegisterPage registers a page route.