beach

package
v0.0.0-...-65d2c91 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 40 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package beach is Beach's HTTP layer: the framework's front door. It is the module root (package beach) rather than a sub-package — services build their main.go against beach.New and the three typed handler shapes.

The builder collapses the boilerplate every service would otherwise repeat: a fixed middleware stack (request log, recover, security headers + CSP, optional session auth), GET /healthz, static file serving with boot-time SHA256 ETags and immutable cache headers, and graceful shutdown. Routes register against typed handler shapes — PageFunc, ActionFunc, StreamFunc — that encode the house rules by construction, with guards (Authed, Role, Can) that make the auth story visible in the route table.

Echo is named in the architecture doc, but the frozen go.mod ships no web framework, so the implementation is stdlib net/http with the Go 1.22 ServeMux pattern router underneath. App.Mux() and App.Raw are the escape hatches for the genuinely weird (payment webhooks, plain http.Handler middleware).

Index

Constants

View Source
const (
	// MsgText is a UTF-8 text frame.
	MsgText = MsgType(websocket.MessageText)
	// MsgBinary is a binary frame.
	MsgBinary = MsgType(websocket.MessageBinary)
)
View Source
const PrefsCookie = prefs.Cookie

PrefsCookie is the cookie carrying a visitor's timing preferences.

View Source
const PrefsPath = prefs.Path

PrefsPath is the framework-owned route that writes that cookie. It is registered by New alongside /healthz.

View Source
const ThemePath = "/_beach/theme.css"

ThemePath is the framework-owned route serving the derived design tokens. The underscore prefix marks it as the framework's rather than an app's, the same way prefs.Path does.

View Source
const ToastTarget = driftwood.ToastTarget

ToastTarget is the DOM id of the page's live region, where error toasts and Patch.Announce messages land. driftwood.Shell renders the region empty on every page — which is what makes patches into it announced, since a live region that arrives with its content is not read out. The kit owns the id because the kit renders the element; this is the alias apps name.

Variables

View Source
var (
	// ErrNotFound renders a 404. Return it when a looked-up resource is absent.
	ErrNotFound = errors.New("beach: not found")

	// ErrForbidden renders a 403. Guards return it; handlers may too.
	ErrForbidden = errors.New("beach: forbidden")

	// ErrUnauthorized renders a 401. Return it when authentication is required
	// and absent (guards normally handle this).
	ErrUnauthorized = errors.New("beach: unauthorized")

	// ErrBadRequest renders a 400. Bind returns it (wrapped in a ValidationError)
	// for malformed input.
	ErrBadRequest = errors.New("beach: bad request")
)

Sentinel errors map to specific HTTP statuses. Wrap them with fmt.Errorf("%w", ...) to add context while keeping the status mapping (errors.Is sees through).

View Source
var ErrSocketClosed = errors.New("beach: socket closed")

ErrSocketClosed is returned by Socket.Write after the connection has closed.

Functions

func AutoDismiss

func AutoDismiss(ctx context.Context) bool

AutoDismiss reports whether notifications may still expire on a timer.

func Bind

func Bind[T any](c *Ctx) (T, error)

Bind decodes and returns a typed value from the request. For a JSON or Datastar request it decodes the JSON body the client posts (Datastar posts its signals as a JSON object); for a normal form submission it maps URL-encoded values by `form:"name"` struct tags. A decode failure becomes a ValidationError (HTTP 400). If T has a Validate() error method it is called after binding, so a handler's domain validation rides along.

func ColorScheme

func ColorScheme(ctx context.Context) prefs.Scheme

ColorScheme reports the visitor's light/dark choice, or prefs.SchemeAuto when they have expressed none and the operating system should decide.

func LiveUpdates

func LiveUpdates(ctx context.Context) bool

LiveUpdates reports whether this request's visitor still wants server-pushed updates. It is the reader a StreamFunc uses when it wants to branch itself; the framework already applies it to every stream, so most handlers never need to call it.

func Relay

func Relay(ctx context.Context, a, b *Socket) error

Relay pumps frames bidirectionally between two sockets until either side closes or ctx is canceled. Binary frames ride WriteLatest (latest-state-wins, matching the simulation-stream contract); text frames ride the ordered queue. A clean close on either side returns nil; both sockets are torn down on return.

Types

type ActionFunc

type ActionFunc func(c *Ctx) (Patches, error)

ActionFunc handles a Datastar-only mutation. Navigation to an action route is a 404; the Datastar-Request check and method discipline are the framework's. The handler does the mutation and returns the patches to apply, which the framework streams over a one-shot SSE response.

type App

type App struct {
	// contains filtered or unexported fields
}

App is a configured Beach application. Build one with New, register routes with Page/Action/Stream/Raw, then Start. The zero App is not usable.

func New

func New(cfg Config) *App

New builds an App from cfg. It wires the static handler (computing boot-time ETags) and registers GET /healthz and the static tree. It does not bind a socket; that happens in Start.

func (*App) Action

func (a *App) Action(pattern string, h ActionFunc, guards ...Guard)

Action registers an ActionFunc at POST pattern. Actions are Datastar-only; a plain navigation gets a 404 from the adapter.

func (*App) AssetURL

func (a *App) AssetURL(path string) string

AssetURL returns the cache-busted URL for a static asset path (e.g. "css/app.css" -> "/static/css/app.css?v=..."). Templates call this so every deploy busts caches without a manifest.

func (*App) Authed

func (a *App) Authed() Guard

Authed requires an authenticated session: a request without one gets 401 and the handler never runs. A PageFunc behind Authed() can assume c.User() is present.

func (*App) Can

func (a *App) Can(permission string) Guard

Can requires the principal to hold the given "resource:action" permission. It needs a principal in context — from a session PrincipalResolver (Config.Principals) or from TokenAuthed() for a bearer caller. With neither, no request has a principal and the guard 401s an anonymous request or 403s an authenticated one lacking the permission, which is the safe failure.

func (*App) Handler

func (a *App) Handler() http.Handler

Handler returns the app as a single http.Handler with the full middleware stack applied. Useful for httptest and for embedding the app in another server.

func (*App) InScope

func (a *App) InScope(scope string) Guard

InScope requires the principal to act within the given owner/customer scope. It registers on a route exactly like Can(...): an anonymous, unscoped, or wrong-scope principal is rejected with 403 before the handler body runs. The scope string is opaque to Beach — the app decides what a scope means.

func (*App) Logger

func (a *App) Logger() *slog.Logger

Logger returns the app's structured logger.

func (*App) Mux

func (a *App) Mux() *http.ServeMux

Mux exposes the underlying ServeMux for advanced wiring (mounting a sub-router, a third-party handler). Prefer Page/Action/Stream/Raw; this is the escape hatch.

func (*App) Page

func (a *App) Page(pattern string, h PageFunc, guards ...Guard)

Page registers a PageFunc at GET pattern. Tabs, filters, pagination and sort reuse this URL with query params — they never get their own routes. Optional guards wrap it outermost-first.

Page("/") is the home page, an exact match — not ServeMux's catch-all (see register). For a true catch-all, register a "/{path...}" wildcard or use Mux().

func (*App) Raw

func (a *App) Raw(method, pattern string, h http.HandlerFunc, guards ...Guard)

Raw is the documented escape hatch: a plain http.HandlerFunc mounted at method+pattern, outside the typed shapes. Payment webhooks live here — they must mount outside auth and the Datastar discipline to run reliably. Guards may still wrap a raw handler when wanted.

func (*App) ReloadTheme

func (a *App) ReloadTheme(ctx context.Context) error

ReloadTheme re-resolves the theme and swaps it in for subsequent requests.

An app calls it after writing a new theme — from an admin screen, or from a pg.Notify listener when another process wrote one. The swap is atomic, so a request either serves the whole old theme or the whole new one, never a mix.

func (*App) Role

func (a *App) Role(role string) Guard

Role requires the session to carry the given role slug: 401 when unauthenticated, 403 when authenticated but lacking the role.

func (*App) Shutdown

func (a *App) Shutdown(ctx context.Context) error

Shutdown triggers graceful shutdown: live WebSockets get close 1001 (going away, their contexts cancel), the HTTP server drains normal requests, and socket handlers are waited on until ctx expires. Hijacked connections are invisible to http.Server.Shutdown, which is why the sockets close first and are waited on explicitly.

func (*App) Socket

func (a *App) Socket(pattern string, h SocketFunc, guards ...Guard)

Socket registers a SocketFunc at GET pattern (WebSocket upgrades ride a GET). Guards run before the upgrade, so a rejection is a plain HTTP 401/403, never a half-open socket. The socket carries payloads that are not hypermedia — UI sync stays on Stream; a page wanting both keeps them side by side.

func (*App) Start

func (a *App) Start(addr string) error

Start binds addr and serves until an interrupt (SIGINT/SIGTERM), then shuts down gracefully within ShutdownTimeout.

func (*App) Stream

func (a *App) Stream(pattern string, h StreamFunc, guards ...Guard)

Stream registers a StreamFunc at GET pattern. The framework runs the SSE loop; the handler only declares topics and catch-up.

func (*App) TokenAuthed

func (a *App) TokenAuthed() Guard

TokenAuthed requires a valid bearer token: it reads the Authorization header, resolves the token to a principal via the configured TokenResolver (Config.Tokens), and attaches that principal to the request context — the same principal a session login would carry, so Can(...) and InScope(...) compose on top. A missing or invalid token (or no configured resolver) gets 401 and the handler never runs.

type CSP

type CSP struct {
	// contains filtered or unexported fields
}

CSP is a small, composable Content-Security-Policy builder. Beach pages are HTML-and-CSS-first with Datastar as the only script, so the default is strict: self for everything, no inline script. Apps widen specific directives for the genuinely needed (e.g. a video CDN for media) via the Allow* methods, which return a copy so a base preset can be shared and extended without mutation.

func CSPDefault

func CSPDefault() CSP

CSPDefault is the strict baseline: everything from 'self', images and media also allow data: URIs, styles allow 'unsafe-inline' (components emit inline style attributes for reserved dimensions and token colors), and object/frame are denied. script-src includes 'unsafe-eval' because Datastar — the framework's one client dependency — evaluates its `data-*` expressions (`@post(...)`, signals) with the Function constructor; without it every Datastar action throws. No external origins; the Datastar client is served from 'self'. Apps widen from here.

func (CSP) Allow

func (c CSP) Allow(directive string, sources ...string) CSP

Allow appends sources to an arbitrary directive. The named-directive helpers below cover the common cases; this is the general form.

func (CSP) AllowConnect

func (c CSP) AllowConnect(sources ...string) CSP

AllowConnect widens connect-src (fetch / SSE / websocket endpoints).

func (CSP) AllowFrame

func (c CSP) AllowFrame(sources ...string) CSP

AllowFrame widens frame-src (embedded iframes).

func (CSP) AllowImg

func (c CSP) AllowImg(sources ...string) CSP

AllowImg widens img-src.

func (CSP) AllowMedia

func (c CSP) AllowMedia(sources ...string) CSP

AllowMedia widens media-src (audio/video), e.g. a Cloudflare Stream origin.

func (CSP) AllowScript

func (c CSP) AllowScript(sources ...string) CSP

AllowScript widens script-src. Reach for this only for a genuinely required third-party script; the house style is Datastar-only.

func (CSP) IsZero

func (c CSP) IsZero() bool

IsZero reports whether the CSP is the zero value (no directives), used by the builder to fall back to CSPDefault.

func (CSP) String

func (c CSP) String() string

String renders the policy as a single header value, directives sorted for deterministic output (stable tests, stable diffs).

type Config

type Config struct {
	// Service names the running service (used in logs and the default Server
	// header). e.g. "live".
	Service string

	// Release reports whether this is a released (production) binary. It selects
	// stable commit-based asset versioning over dev timestamps, hardens cookies,
	// and silences the dev page-size warnings.
	Release bool

	// CSP is the Content-Security-Policy preset applied by the secure-headers
	// middleware. A zero CSP falls back to CSPDefault().
	CSP CSP

	// Static is the filesystem served under /static (with boot-time ETags and
	// immutable cache headers). When nil, the framework serves the embedded
	// internal/view/static tree (app.css, the Datastar client, and the chart
	// modules).
	Static fs.FS

	// Sessions, when non-nil, enables session-backed auth: OptionalAuth runs in
	// the middleware stack and guards (Authed/Role) resolve against it. Left nil,
	// the app runs without a database and every principal is anonymous (nil),
	// unless AnonymousSessions is set.
	Sessions *session.Store

	// AnonymousSessions, when non-nil, enables a cookie-only anonymous identity:
	// the middleware mints a stable per-browser id (no database) and c.Principal()
	// returns a well-defined anonymous principal carrying it, instead of nil. It is
	// the DB-less path for a fully-ephemeral app that wants a stable visitor
	// identity without minting its own cookie. The anonymous principal holds no
	// roles or permissions, so guards (Authed/Role/Can) still reject it. Ignored
	// when Sessions is set — a DB-backed app resolves real identities there.
	AnonymousSessions *session.AnonStore

	// Principals, when non-nil, resolves a rich auth.Principal from the
	// session-bound user id. Optional; without it c.User() still works from the
	// session and c.Principal() is nil.
	Principals PrincipalResolver

	// Tokens, when non-nil, resolves a rich auth.Principal from a raw bearer
	// token. It backs the TokenAuthed() guard for non-interactive callers
	// (service accounts, CLIs). Without it TokenAuthed() rejects every request,
	// which is the safe failure.
	Tokens TokenResolver

	// Theme pins the design tokens this app serves, overriding the preset the
	// framework ships. Nil falls through to ThemeSource, then to the preset.
	Theme *theme.Theme

	// ThemeSource resolves the theme at boot and on App.ReloadTheme — the hook
	// for an app that stores its palette rather than compiling it in. Ignored
	// when Theme is set.
	//
	// A resolving *function* rather than a table the framework owns: the
	// framework owns tables for auth and sessions and nothing else, and this way
	// an app can back its theme with a row, a file or an env var, exactly as it
	// already does for principals.
	ThemeSource ThemeSource

	// Hub is the in-memory topic fan-out backing StreamFunc subscriptions. A nil
	// hub disables live events (catch-up still runs); set one to serve realtime
	// streams.
	Hub *hub.Hub

	// Healthz is the readiness probe behind GET /healthz. A nil probe always
	// reports healthy (200 ok) — fine for a database-less app.
	Healthz HealthFunc

	// Logger is the structured logger used by the request-logging and recover
	// middleware. Defaults to slog.Default().
	Logger *slog.Logger

	// ShutdownTimeout bounds graceful shutdown. Defaults to 15s.
	ShutdownTimeout time.Duration

	// SSECompression overrides the default SSE compression mode for StreamFunc /
	// ActionFunc responses. The zero value is the gzip default.
	SSECompression SSEMode

	// Sockets tunes the WebSocket machinery behind App.Socket (message size
	// cap, keepalive cadence, write-queue depth, allowed origins). The zero
	// value applies the documented defaults; same-origin only.
	Sockets SocketConfig

	// Locales, when non-nil, resolves each request's locale (cookie, then
	// Accept-Language, then the catalog default) and carries it and the catalog
	// on the request context. Two things then follow without any further
	// wiring: i18n.T resolves this app's strings, and the driftwood page shell
	// declares the matching <html lang> and dir — which is what a screen reader
	// reads to pick its voice and pronunciation rules (WCAG 3.1.1).
	//
	// New also registers it with i18n.SetDefault, so i18n.T resolves this app's
	// strings *off* a request too — inside a hub.Ticker, a background job, any
	// render with no request context to carry the catalog. Without that the
	// promise above holds only on the request path, and a fragment pushed over
	// SSE renders its own catalog keys as literal text.
	//
	// Left nil, the app runs monolingual: i18n.T falls back to the framework's
	// embedded catalog, the shell declares lang="en", and the feature costs
	// nothing. The middleware runs outermost, before request logging, so a
	// logged or recovered request already knows its locale.
	Locales *i18n.Catalog

	// Middleware are app-supplied net/http wrappers applied around the whole
	// handler, outside the fixed framework stack. They run outermost-first: the
	// first entry is the outermost wrapper, so it sees the request first and the
	// response last. A wrapper here runs before request logging, recover, secure
	// headers and auth — the place for cross-cutting concerns (an i18n locale
	// resolver, a custom request id) the framework does not own. Left nil, the
	// handler is exactly the fixed stack, unchanged.
	Middleware []func(http.Handler) http.Handler
}

Config configures a new App. The zero value is usable: every field worth setting has a sensible default.

type Ctx

type Ctx struct {
	W http.ResponseWriter
	R *http.Request
	// contains filtered or unexported fields
}

Ctx is the request-scoped context the typed handlers receive. It wraps the http.ResponseWriter and *http.Request and exposes the session user and the auth principal, plus the small helpers (path/query params, binding) the house handlers lean on. Construct one only through the framework; handlers receive *Ctx, never build it.

func (*Ctx) AnonID

func (c *Ctx) AnonID() (string, bool)

AnonID returns the stable cookie-only anonymous session id and whether one is present. It is set by Config.AnonymousSessions; an app without it (or behind a real login) has no anonymous id. Apps key ephemeral per-visitor state on it.

func (*Ctx) Context

func (c *Ctx) Context() context.Context

Context returns the request's context.Context, for cancellation and deadlines.

func (*Ctx) FormValue

func (c *Ctx) FormValue(name string) string

FormValue returns a POST/PUT form value (parsing the body on first use).

func (*Ctx) Header

func (c *Ctx) Header(name string) string

Header returns a request header value.

func (*Ctx) IsDatastar

func (c *Ctx) IsDatastar() bool

IsDatastar reports whether the request came from Datastar's fetch client. The PageFunc adapter uses this to choose full-document vs. fragment; handlers that branch manually can read it too.

func (*Ctx) MustPrincipal

func (c *Ctx) MustPrincipal() *Principal

MustPrincipal returns the principal (possibly nil). The *Principal methods are nil-safe, so this is convenient inside guarded handlers.

func (*Ctx) MustUser

func (c *Ctx) MustUser() User

MustUser returns the session user, assuming a guard guaranteed it. It returns the zero User when unauthenticated; use it only inside guarded handlers.

func (*Ctx) Param

func (c *Ctx) Param(name string) string

Param returns a path parameter captured by the ServeMux pattern (e.g. the "{id}" segment of "/coins/purchase/{id}"). Missing params return "".

func (*Ctx) Principal

func (c *Ctx) Principal() (*Principal, bool)

Principal returns the rich auth principal and whether one is present. It is nil for an unauthenticated request and for apps that configured no PrincipalResolver. With Config.AnonymousSessions it is the cookie-only anonymous principal (IsAnonymous() true) instead of nil. A nil principal answers false to every Can/HasRole check, so handlers can call methods on it without a nil guard.

func (*Ctx) Query

func (c *Ctx) Query(name string) string

Query returns a URL query parameter (the first value), or "" when absent. Tabs, filters, pagination, and sort live in query params on the page URL — they never get their own routes.

func (*Ctx) Redirect

func (c *Ctx) Redirect(status int, location string)

Redirect writes an HTTP redirect to the given location with the given status (use http.StatusSeeOther for POST-redirect-GET). For Datastar requests prefer returning a Patches that updates the URL; this is the plain-navigation form.

func (*Ctx) SetCookie

func (c *Ctx) SetCookie(cookie *http.Cookie)

SetCookie writes a Set-Cookie response header. An action that mints a session calls this before returning its Patches (the response headers are flushed when the SSE stream opens, after the handler body runs), so a Patch{Redirect: ...} can carry the cookie on the same response — the post-login bounce without a Raw handler.

func (*Ctx) SetHeader

func (c *Ctx) SetHeader(name, value string)

SetHeader sets a response header. Useful for cache directives on a fragment response or a redirect target.

func (*Ctx) User

func (c *Ctx) User() (User, bool)

User returns the session identity and whether one is present. Anonymous requests return the zero User and false. Behind a guard (Authed/Role/Can) the user is guaranteed present, so guarded handlers can ignore the bool.

type DialOpt

type DialOpt func(*dialConfig)

DialOpt configures DialSocket.

func WithDialHeader

func WithDialHeader(h http.Header) DialOpt

WithDialHeader sets extra HTTP headers on the handshake request (an Origin, a bearer token for a TokenAuthed backend).

func WithDialSocketConfig

func WithDialSocketConfig(cfg SocketConfig) DialOpt

WithDialSocketConfig overrides the SocketConfig used for the dialed side (keepalive cadence, queue depth). The zero-value default applies otherwise.

type Guard

type Guard func(http.Handler) http.Handler

Guard wraps a handler with an access check. It runs after the auth middleware has populated the request context, so it can read the user/principal; on failure it writes the mapped error (401/403) and the wrapped handler never runs. Authed/Role/Can return Guards.

type HealthFunc

type HealthFunc func(ctx context.Context) error

HealthFunc is the readiness probe behind /healthz. Returning an error renders a 503; nil renders 200.

type HubEvent

type HubEvent = hub.Event

hubEvent re-exports hub.Event so producers that publish into a Stream's topics from a beach handler do not import hub directly. It is a type alias, so a hub.Event passes wherever a beach.HubEvent is wanted and vice versa.

type MsgType

type MsgType int

MsgType is a WebSocket data-frame type. Values map to the wire opcodes.

type PageFunc

type PageFunc func(c *Ctx) (View, error)

PageFunc handles anything you can navigate to. It returns one View that knows how to render both ways: the framework writes the full document on a normal GET and patches the fragment on a Datastar request. You cannot forget the branch, and a separate fragment route has nothing to attach to.

type Patch

type Patch struct {
	// Fragment is the component to render and patch in.
	Fragment templ.Component

	// Target is the DOM id to patch into (without '#'). Empty patches by the
	// fragment's own element id.
	Target string

	// Mode selects the merge mode; zero is the default outer morph.
	Mode PatchMode

	// Signals, when non-nil, JSON-marshals to a data-signals patch sent alongside
	// the element patch (e.g. to clear a form's input signals after a submit).
	Signals any

	// Redirect, when non-empty, navigates the client to the given URL through the
	// Datastar SSE flow (a location script). It is the escape hatch for an action
	// that must redirect — a post-login bounce — without dropping to a Raw handler.
	// Combine it with SetHeader/SetCookie on the *Ctx to set a session cookie on
	// the same response. An empty Redirect is a no-op.
	Redirect string

	// Script, when non-empty, runs the given JavaScript in the client browser
	// (Datastar ExecuteScript). It is the escape hatch for an action that must
	// drive the client directly. An empty Script is a no-op.
	Script string

	// ViewTransition applies this patch inside the browser View Transitions API
	// so CSS ::view-transition-* rules animate the change.
	ViewTransition bool

	// Announce, when non-empty, appends the message to the page's live region
	// so a screen reader reads it out. It is how a server-driven change tells
	// someone who cannot see it that anything happened — "12 results", "saved",
	// "3 items removed" (WCAG 4.1.3 Status Messages).
	//
	// It needs the region to already exist, which driftwood.Shell renders on
	// every page; a page building its own shell renders driftwood.LiveRegion
	// itself. The message is text, not markup, and is appended rather than
	// replacing what is there, so a burst of updates is read in order.
	//
	// Use it for status, not for errors: a failure already streams a toast
	// through the same region, and Alert carries role=alert when something must
	// interrupt.
	Announce string
}

Patch is a single fragment-to-target update. It is the unit an ActionFunc returns (as Patches) and the unit a StreamFunc's catch-up pushes. A Patch with a nil Fragment and PatchRemove mode removes the Target.

type PatchMode

type PatchMode string

PatchMode selects how a fragment is merged into the DOM. It mirrors the Datastar element-patch modes; the zero value is the default outer morph.

const (
	// PatchOuter morphs the target element itself (default).
	PatchOuter PatchMode = "outer"
	// PatchInner replaces the target's inner HTML.
	PatchInner PatchMode = "inner"
	// PatchReplace hard-replaces the target element.
	PatchReplace PatchMode = "replace"
	// PatchPrepend inserts the fragment as the target's first children.
	PatchPrepend PatchMode = "prepend"
	// PatchAppend inserts the fragment as the target's last children.
	PatchAppend PatchMode = "append"
	// PatchBefore inserts the fragment before the target.
	PatchBefore PatchMode = "before"
	// PatchAfter inserts the fragment after the target.
	PatchAfter PatchMode = "after"
	// PatchRemove removes the target element.
	PatchRemove PatchMode = "remove"
)

type Patcher

type Patcher interface {
	// Patch renders a single Patch onto the stream.
	Patch(p Patch) error
}

Patcher is the narrow interface a StreamFunc's CatchUp receives: it can patch a fragment into a target. It is satisfied by the live SSE stream, so a catch-up replay writes through the same compressed connection as live events. The interface keeps catch-up code from depending on the whole SSE surface.

type Patches

type Patches []Patch

Patches is the return type of an ActionFunc: an ordered list of DOM patches the framework streams to the client over a one-shot SSE response. Returning an empty Patches is valid (a mutation with no visible change).

type Prefs

type Prefs = prefs.Prefs

Prefs re-exports the preference type so a handler names one beach.Prefs rather than reaching across packages for a two-field struct.

func PrefsFrom

func PrefsFrom(ctx context.Context) Prefs

PrefsFrom reads the visitor's preferences from ctx, defaulting to everything on.

type Principal

type Principal = auth.Principal

Principal is re-exported so handler signatures and guard call sites name a single beach.Principal rather than reaching into the auth package. It is the resolved identity for an authenticated request (user id, username, roles, flattened permissions).

type PrincipalResolver

type PrincipalResolver func(ctx context.Context, userID int64) (*Principal, error)

PrincipalResolver turns a session user id into a rich principal. It is called once per authenticated request when Config.Principals is set. Returning a nil principal (and nil error) leaves the request anonymous at the principal level while still carrying the session user.

type SSEMode

type SSEMode = datastar.SSECompression

SSEMode re-exports the datastar package's compression mode so an app names a single beach.SSE* constant in Config rather than reaching across packages.

const (
	// SSECompressionGzip is the default: gzip at the fastest level, sync-flushed
	// per event.
	SSECompressionGzip SSEMode = datastar.SSECompressionGzip
	// SSECompressionLight is the low-memory Huffman-only fallback.
	SSECompressionLight SSEMode = datastar.SSECompressionLight
	// SSECompressionOff disables compression.
	SSECompressionOff SSEMode = datastar.SSECompressionOff
)

type Socket

type Socket struct {
	// contains filtered or unexported fields
}

Socket is an accepted (or dialed) WebSocket connection. The framework owns the wire: one writer goroutine serializes all outgoing frames, and a read pump keeps a reader active at all times so ping/pong and close frames are handled even for a write-only handler. Handlers use Read/Write/WriteLatest; they never see the underlying connection.

func DialSocket

func DialSocket(ctx context.Context, url string, opts ...DialOpt) (*Socket, error)

DialSocket dials a WebSocket URL (ws:// or wss://) and returns the same *Socket the server side gets, pumps and keepalive included. It backs the relay pattern — an app terminates the public socket via App.Socket and relays frames to a private backend worker socket — and the test suite. The caller owns the socket and must Close it.

func (*Socket) Close

func (s *Socket) Close(code int, reason string) error

Close performs the close handshake with the given status code (e.g. 1000 for normal) and reason, then tears the socket down. Subsequent closes are no-ops returning the first result.

func (*Socket) Context

func (s *Socket) Context() context.Context

Context returns a context canceled when the socket closes (peer close, write failure, keepalive timeout, server shutdown). Push loops select on it.

func (*Socket) Read

func (s *Socket) Read() (MsgType, []byte, error)

Read blocks until the next data message arrives and returns it. Ping, pong and close frames are handled internally and never surface here. On close it returns the connection's terminal error (a clean peer close is still an error, as with io.EOF), or ErrSocketClosed when this side closed first.

func (*Socket) Write

func (s *Socket) Write(typ MsgType, p []byte) error

Write enqueues an ordered frame (input acks, control messages). It blocks while the bounded queue is full and returns ErrSocketClosed once the socket is down. Delivery is serialized with WriteLatest frames by the single writer.

func (*Socket) WriteLatest

func (s *Socket) WriteLatest(p []byte)

WriteLatest offers a binary frame in latest-state-wins mode: only the newest undelivered frame is kept, so a slow client skips frames instead of building a queue. It never blocks. This is the shape for simulation state streams.

type SocketConfig

type SocketConfig struct {
	// MaxMessageBytes caps a single incoming message. Default 1 MiB. A peer
	// exceeding it gets close 1009 (message too big).
	MaxMessageBytes int64

	// PingInterval is the framework-owned keepalive cadence. Default 20s.
	PingInterval time.Duration

	// PongTimeout bounds the wait for a pong before the peer is declared dead
	// and the connection torn down. Default 30s.
	PongTimeout time.Duration

	// WriteQueueLen bounds the ordered Write queue; a full queue blocks the
	// caller. Default 64. WriteLatest bypasses this queue (depth-1 mailbox).
	WriteQueueLen int

	// Origins lists additional allowed Origin host patterns (path.Match
	// syntax, e.g. "app.example.com"). Empty means same-origin only — browser
	// WS ignores CORS, so this check is the framework's.
	Origins []string
}

SocketConfig tunes the framework-owned socket machinery. The zero value is usable; every field defaults sensibly.

type SocketFunc

type SocketFunc func(c *Ctx, s *Socket) error

SocketFunc owns an upgraded WebSocket connection for its lifetime. It runs after a successful upgrade (guards run before, so a rejection is plain HTTP, never a half-open socket) and holds the connection for as long as it runs. Returning nil closes with 1000 (normal); returning an unexpected error closes with 1011 and logs. A peer close, canceled context, or ErrSocketClosed returned from the read loop counts as normal.

type StreamFunc

type StreamFunc func(c *Ctx) (Sub, error)

StreamFunc declares an SSE subscription. It returns a Sub (topics + optional catch-up); the framework runs the loop — subscribe to the hub, replay the since-cursor catch-up, select over the hub channel and the request context, flush per event, and clean up on disconnect.

type Sub

type Sub struct {
	// Topics are the hub topics this stream subscribes to. Events published to any
	// of them are written to the client as they arrive.
	Topics []string

	// CatchUp, when non-nil, runs once after subscribe and before the live loop.
	// It replays missed patches given the client's ?since= cursor (read by the
	// handler from c.Query("since")), writing through the same Patcher the live
	// loop uses. This is the completeness half of the liveness/completeness split.
	CatchUp func(since string, p Patcher) error

	// Compression overrides the app-default SSE compression mode for this stream.
	// nil uses the app default.
	Compression *SSEMode
}

Sub is what a StreamFunc returns: a declaration of the hub topics to subscribe to and an optional catch-up replay. The framework owns the SSE loop — subscribe, run the since-cursor catch-up, select over the hub channel and the request context, flush per event, clean up — so a stream handler is a declaration, not 200 lines of plumbing.

type ThemeSource

type ThemeSource func(ctx context.Context) (theme.Theme, error)

ThemeSource resolves the theme for a running app. It is called at boot and on App.ReloadTheme, never per request.

It is a function rather than a table because the framework does not own one. It owns tables for auth and sessions and nothing else, and a resolver lets an app back its theme with a row, a file, or an environment variable — exactly as it already does for principals via Config.Principals.

type TokenResolver

type TokenResolver func(ctx context.Context, token string) (*Principal, error)

TokenResolver verifies a raw bearer token and returns the principal it resolves to. It backs the TokenAuthed() guard. A non-nil error (or a nil principal) means the token is invalid; the guard rejects with 401. It wraps auth.Authenticator.ResolveToken.

type User

type User = session.User

User is the small session identity (id + role slugs). A handler usually reads the richer Principal, but User is always available when a session is present.

type ValidationError

type ValidationError struct {
	// Fields maps a form field name to its human-readable error. A general
	// (non-field) message uses the empty-string key.
	Fields map[string]string
}

ValidationError is a field-keyed validation failure returned by Bind and by handlers that validate input. On a Datastar request the framework renders it as inline field errors; on navigation it folds into the error page. It maps to HTTP 400.

func Invalid

func Invalid(field, msg string) *ValidationError

Invalid is a convenience constructor for a single-field ValidationError.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements error.

func (*ValidationError) Is

func (e *ValidationError) Is(target error) bool

Is reports ValidationError as a bad-request error so errors.Is(err, ErrBadRequest) works for the status mapping.

type View

type View struct {
	// Page is the full HTML document rendered on navigation (a normal GET). It is
	// subject to the 14KB rule; heavier content ships as a deferred section.
	Page templ.Component

	// Fragment is the component patched in on a Datastar request. When nil, the
	// framework patches Page instead (a page whose fragment is the whole document
	// — fine for small pages, though most set an explicit Fragment + Target).
	Fragment templ.Component

	// Target is the DOM id the Fragment patches into (without the leading '#').
	// Empty means "patch by the fragment's own element id" (Datastar's default
	// outer-morph), which is the common case when the fragment carries its id.
	Target string

	// Mode overrides the patch mode for the Datastar branch (replace, inner,
	// append, ...). Zero value uses the framework default (outer morph).
	Mode PatchMode

	// Status overrides the HTTP status for the navigation branch (e.g. 404 for a
	// not-found page rendered as a real page). Zero means 200.
	Status int

	// ViewTransition, on the Datastar branch, applies the patch inside the browser
	// View Transitions API (document.startViewTransition), so CSS
	// ::view-transition-* rules animate the change. No effect on navigation.
	ViewTransition bool
}

View is what a PageFunc returns: a description that knows how to render both ways. On a normal navigation the framework writes Page (the full document); on a Datastar request it patches Fragment into Target. A separate fragment route has nothing to attach to — the dual-purpose branch is the framework's, not the handler's, which is the whole point of the type.

func Swap

func Swap(target string, page, fragment templ.Component) View

Swap builds the View for a page that participates in SPA-style navigation (the client half is in pkg/datastar: Navigate / PopstateNav / ActiveWhen). On a full page load the framework renders page (the whole document, shell included); on a Datastar nav it streams fragment into the target region's inner HTML under a browser view transition, so the persistent shell stays put and only the main content slides. target is the region element's id (without '#').

return beach.Swap("main", FullPage(v), pageBody(v)), nil

Directories

Path Synopsis
Package view owns the framework's own front-end source: the Tailwind input stylesheet under css/ and the compiled, served tree under static/.
Package view owns the framework's own front-end source: the Tailwind input stylesheet under css/ and the compiled, served tree under static/.

Jump to

Keyboard shortcuts

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