runtime

package
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 24, 2026 License: MIT Imports: 17 Imported by: 0

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

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

func AssetManifest() *assets.Manifest

AssetManifest returns the loaded asset manifest or nil. Exposed for debugging/admin purposes.

func CSRFMiddleware

func CSRFMiddleware(next http.Handler) http.Handler

CSRFMiddleware injects and validates CSRF tokens.

func DevAddr

func DevAddr(fallback string) string

DevAddr returns the address to listen on in development mode. It checks the STOIC_DEV_PORT environment variable first, then falls back.

func LoggerMiddleware

func LoggerMiddleware(next http.Handler) http.Handler

LoggerMiddleware logs incoming requests.

func RecoverMiddleware

func RecoverMiddleware(next http.Handler) http.Handler

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 RequestID

func RequestID(ctx context.Context) string

RequestID extracts the request ID from context.

func RequestIDMiddleware

func RequestIDMiddleware(next http.Handler) http.Handler

RequestIDMiddleware adds a unique request ID to each request.

func SessionMiddleware

func SessionMiddleware(next http.Handler) http.Handler

SessionMiddleware ensures a session cookie exists.

func TimingMiddleware

func TimingMiddleware(next http.Handler) http.Handler

TimingMiddleware records action dispatch timing.

Types

type AssetOption

type AssetOption func(http.Handler) http.Handler

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

type Middleware func(http.Handler) http.Handler

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

func LoadManifest(manifestPath string) Option

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

func WithAssetHandler(h http.Handler) Option

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

func WithBasePath(p string) Option

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

func WithDevFSRoot(root string) Option

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 WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger.

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 NewServer

func NewServer(opts ...Option) *Server

NewServer creates a new Stoic runtime server.

func (*Server) HandleError added in v0.3.0

func (s *Server) HandleError(w http.ResponseWriter, r *http.Request, code int, message string)

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

func (s *Server) Handler() http.Handler

Handler returns the fully-wrapped http.Handler for the server. Unmatched routes automatically render through the registered error handlers.

func (*Server) ListenAndStart

func (s *Server) ListenAndStart(addr string) error

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) Mux

func (s *Server) Mux() *http.ServeMux

Mux returns the underlying http.ServeMux for registering custom routes.

func (*Server) RegisterAction

func (s *Server) RegisterAction(info stoic.ActionInfo)

RegisterAction registers an action with the runtime.

func (*Server) RegisterHandler

func (s *Server) RegisterHandler(path string, handler http.Handler)

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.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL