Documentation
¶
Overview ¶
Package pw is the stable application-facing Popcorn Web API.
Index ¶
- Constants
- Variables
- func ActionSelector(r *http.Request, field string) string
- func AssembleOpenAPI() ([]byte, error)
- func Authenticated(r *http.Request) bool
- func AuthenticatedContext(ctx context.Context) bool
- func Command[T any]() (T, bool)
- func Config[T any](r *http.Request) T
- func ConfigContext[T any](ctx context.Context) T
- func Context(r *http.Request) context.Context
- func DB(r *http.Request) (*sql.DB, bool)
- func DBContext(ctx context.Context) (*sql.DB, bool)
- func DBDriver(r *http.Request) (string, bool)
- func DBDriverContext(ctx context.Context) (string, bool)
- func DeclaredLocales() []string
- func Development() bool
- func DispatchAction(w http.ResponseWriter, r *http.Request, handler http.HandlerFunc)
- func Env() string
- func EnvironmentDeclared() bool
- func FormValue(r *http.Request, key string) string
- func IsBot(r *http.Request) bool
- func LocalePath(r *http.Request, locale Locale, path string) string
- func LocalePathContext(ctx context.Context, locale Locale, path string) string
- func Middlewares(handler http.Handler, option ...Option) (http.Handler, error)
- func MovedPermanently(url string) error
- func OpenAPIJSON(w http.ResponseWriter, r *http.Request)
- func OpenSessionBackend(ctx context.Context, config SessionConfig, resources SessionResources) (session.Backend, error)
- func PackageAssetURL(module, name string) (string, bool)
- func Parse[T any](r *http.Request) (T, error)
- func ParseConfig() error
- func PathValue(r *http.Request, key string) string
- func PermanentRedirect(url string) error
- func PrepareTestRuntime(handler http.Handler, configs pwtestbridge.Configs, ...) (pwtestbridge.Prepared, error)
- func PublicAssetURL(name string) string
- func QueryLookup(query QueryValues, key string) (string, bool)
- func QueryLookupAll(query QueryValues, key string) []string
- func QueryValue(r *http.Request, key string) (string, bool)
- func RateLimitStores() []string
- func Redirect(w http.ResponseWriter, r *http.Request, url string, status int)
- func RedirectSeeOther(w http.ResponseWriter, r *http.Request, url string)
- func Redraw[P ReloadablePage](w http.ResponseWriter, r *http.Request, page func(P) HTMLFragment) bool
- func RedrawComponents(w http.ResponseWriter, r *http.Request, components ...htmlupdate.Reloadable) bool
- func RegisterConfig[T any](prefix string)
- func RegisterExtension(extension Extension)
- func RegisterHTMLDocument(wrapper HTMLWrapper)
- func RegisterHTMLErrorPage(resolve HTMLErrorPage)
- func RegisterMiddleware(slot Slot, name string, middleware Middleware)
- func RegisterPackage(pkg Package)
- func RegisterPageActions(pattern string, actions ...PageAction)
- func RegisterRateLimitStore(name string, factory RateLimitStoreFactory)
- func RegisterReloadable(components ...htmlupdate.Reloadable) error
- func RegisterSessionBackend(name string, factory SessionBackendFactory)
- func RegisterSessionStore[T any](key string, placement session.Placement, options ...session.SlotOption)
- func RegisterSubCommand[T any](name, help string)
- func ReservedSignalName(name string) bool
- func Run(ctx context.Context, handler http.Handler, option ...Option) error
- func RunFrameworkAction() (handled bool, err error)
- func RuntimeScriptURL() string
- func ScaffoldEnv() (string, error)
- func ScaffoldTOML() (string, error)
- func ScalarUI(specURL string) http.Handler
- func SeeOther(url string) error
- func SelectDB(r *http.Request, group string) context.Context
- func SelectDBContext(ctx context.Context, group string) context.Context
- func SelectSessionDB(r *http.Request) (context.Context, error)
- func SelectSessionDBContext(ctx context.Context) (context.Context, error)
- func SelectWriteDB(r *http.Request) (context.Context, error)
- func SelectWriteDBContext(ctx context.Context) (context.Context, error)
- func SessionBackends() []string
- func SessionCookiePolicy(config SessionConfig) (session.CookieOptions, error)
- func SessionKeyring(config SessionKeyringConfig) (*session.Keyring, error)
- func SessionManager() *session.Manager
- func SessionPrune() func(context.Context, time.Time, int) (int64, error)
- func SessionRegistry(extra ...func(*session.Registry) error) (*session.Registry, error)
- func SetConfigLoadOptions(options configbind.LoadOptions)
- func SetLocale(w http.ResponseWriter, locale Locale)
- func SetOpenAPIInfo(info OpenAPIInfo) error
- func SetRoute(w http.ResponseWriter, r *http.Request)
- func SetSocketDefaults(opts SocketOptions)
- func SetStreamErrorHandler(fn func(error))
- func SnapshotTestConfigs() (pwtestbridge.Configs, error)
- func SpanID(r *http.Request) string
- func SpanIDContext(ctx context.Context) string
- func SubCommand[T any](name, help string)
- func SwaggerUI(specURL string) http.Handler
- func TemporaryRedirect(url string) error
- func TraceID(r *http.Request) string
- func TraceIDContext(ctx context.Context) string
- func Traced(r *http.Request) bool
- func TracedContext(ctx context.Context) bool
- func Transaction(r *http.Request, fn func(context.Context) error) error
- func TransactionContext(ctx context.Context, fn func(context.Context) error) error
- func UpdateBuildID() string
- func WantsLive(r *http.Request) bool
- func WantsUpdate(r *http.Request) bool
- func WantsValue(r *http.Request) bool
- func WebSocket[In, Out any](w http.ResponseWriter, r *http.Request, fn func(*Socket[In, Out]) error) error
- func WebSocketWith[In, Out any](w http.ResponseWriter, r *http.Request, opts SocketOptions, ...) error
- func WithLogAttributes(ctx context.Context, attributes ...Attribute) context.Context
- func WriteAPI[T any](w http.ResponseWriter, r *http.Request, value T)
- func WriteHTML(w http.ResponseWriter, r *http.Request, leaf HTMLFragment)
- func WriteHTMLChain(w http.ResponseWriter, r *http.Request, wrappers []HTMLWrapper, ...)
- func WriteHTMLFragment(w http.ResponseWriter, r *http.Request, fragment HTMLFragment)
- func WriteHTMLPage(w http.ResponseWriter, r *http.Request, wrappers []HTMLWrapper, ...)
- func WriteProblem(w http.ResponseWriter, r *http.Request, err error)
- func WriteScaffoldEnv(w io.Writer) error
- func WriteScaffoldTOML(w io.Writer) error
- func WriteStatus[T any](w http.ResponseWriter, r *http.Request, status int, value T)
- func WriteStream[T any](w http.ResponseWriter, r *http.Request, fn func(*Stream[T]) error)
- func WriteUpdate(w http.ResponseWriter, r *http.Request, status int, regions ...UpdateRegion)
- func WriteUpdateNavigate(w http.ResponseWriter, r *http.Request, url string)
- type ActionDeclaration
- type AsyncError
- type Attribute
- func Bool(key string, value bool) Attribute
- func Duration(key string, value time.Duration) Attribute
- func Err(err error) Attribute
- func Float64(key string, value float64) Attribute
- func Int(key string, value int) Attribute
- func Int64(key string, value int64) Attribute
- func String(key, value string) Attribute
- type Authentication
- type CSRFConfig
- type CacheKey
- type CacheStats
- type CacheStore
- type CacheTagger
- type Extension
- type FieldError
- type HSTSConfig
- type HTMLCacheConfig
- type HTMLConfig
- type HTMLErrorPage
- type HTMLFragment
- type HTMLOption
- type HTMLUpdateConfig
- type HTMLWrapper
- type Level
- type Lifecycle
- type Locale
- type LocaleChoice
- type Log
- type MetricsConfig
- type Middleware
- type MiddlewareConfig
- type ObservabilityConfig
- type OpenAPIInfo
- type Option
- type OtelExportConfig
- type Package
- type PageAction
- type Pending
- type Problem
- func BadRequest(values ...any) Problem
- func Conflict(values ...any) Problem
- func Forbidden(values ...any) Problem
- func InternalServerError(values ...any) Problem
- func NotFound(values ...any) Problem
- func PayloadTooLarge(values ...any) Problem
- func RateLimited(rate RateLimit, values ...any) Problem
- func ServiceUnavailable(values ...any) Problem
- func TooManyRequests(values ...any) Problem
- func Unauthorized(values ...any) Problem
- func Validation(fields ...FieldError) Problem
- type PublicConfig
- type PublicError
- type QueryLogConfig
- type QueryValues
- type RDBConfig
- type RDBConnectionConfig
- type RateLimit
- type RateLimitConfig
- type RateLimitCounter
- type RateLimitRedisConfig
- type RateLimitStoreFactory
- type ReloadablePage
- type SecurityConfig
- type SecurityHeadersConfig
- type ServeMux
- type ServerConfig
- type SessionBackendFactory
- type SessionConfig
- type SessionCookieConfig
- type SessionCookieStoreConfig
- type SessionDynamoConfig
- type SessionKeyringConfig
- type SessionRDBConfig
- type SessionRedisConfig
- type SessionResources
- type Signal
- type SignalPayload
- type Slot
- type Socket
- type SocketOptions
- type Span
- func StartSpan(r *http.Request, name string, attributes ...Attribute) (context.Context, *Span)
- func StartSpanContext(ctx context.Context, name string, attributes ...Attribute) (context.Context, *Span)
- func StartSpanKind(r *http.Request, name string, kind SpanKind, attributes ...Attribute) (context.Context, *Span)
- func StartSpanKindContext(ctx context.Context, name string, kind SpanKind, attributes ...Attribute) (context.Context, *Span)
- type SpanKind
- type Stream
- type TraceConfig
- type UnsetPendingError
- type UpdateRegion
Constants ¶
const ( APIDocScalar = apidoc.APIDocScalar APIDocSwagger = apidoc.APIDocSwagger )
Supported server.api_doc values. An empty value disables the endpoint.
const ( // BootLogAuto renders the tree on an interactive terminal and the single // structured record everywhere else. BootLogAuto = "auto" // BootLogTree writes the human-readable startup summary to stderr. BootLogTree = "tree" // BootLogRecord emits one structured log record through the default logger. BootLogRecord = "record" // BootLogOff suppresses the startup summary. BootLogOff = "off" )
Boot log formats. Startup facts are collected during configuration parsing and emitted once, when the framework knows whether it owns a listener.
const ( SessionBackendRDB = sessionconfig.SessionBackendRDB SessionBackendCookie = sessionconfig.SessionBackendCookie SessionBackendDevVolatile = sessionconfig.SessionBackendDevVolatile SessionBackendDevPersist = sessionconfig.SessionBackendDevPersist SessionBackendRedis = sessionconfig.SessionBackendRedis SessionBackendDynamo = sessionconfig.SessionBackendDynamo SessionBackendFirestore = sessionconfig.SessionBackendFirestore )
Session storage backends. They name which server backend a server-placed slot uses, never whether a slot is server-placed, which RegisterSessionStore states instead.
const ( EnvDevelopment = pwconfig.EnvDevelopment EnvStaging = pwconfig.EnvStaging EnvProduction = pwconfig.EnvProduction )
Well-known runtime environments. Any other lowercase token is also accepted.
const ( SlotMetrics = pwruntime.SlotMetrics SlotTracing = pwruntime.SlotTracing SlotResources = pwruntime.SlotResources SlotClientAddress = pwruntime.SlotClientAddress SlotRequestID = pwruntime.SlotRequestID SlotAccessLog = pwruntime.SlotAccessLog SlotRecover = pwruntime.SlotRecover SlotRateLimitProcess = pwruntime.SlotRateLimitProcess SlotSecurityHeaders = pwruntime.SlotSecurityHeaders SlotRequestTimeout = pwruntime.SlotRequestTimeout SlotMaxRequestBody = pwruntime.SlotMaxRequestBody SlotPublicAssets = pwruntime.SlotPublicAssets SlotOperational = pwruntime.SlotOperational SlotStorage = pwruntime.SlotStorage SlotSignedStorage = pwruntime.SlotSignedStorage SlotSession = pwruntime.SlotSession SlotAuthentication = pwruntime.SlotAuthentication SlotRateLimit = pwruntime.SlotRateLimit SlotCSRF = pwruntime.SlotCSRF SlotGuard = pwruntime.SlotGuard SlotAPIDoc = pwruntime.SlotAPIDoc )
const ( // UpdateHeaderPrefix yields Pw-Render, Pw-Manifest, and Pw-Build. UpdateHeaderPrefix = pwruntime.UpdateHeaderPrefix // UpdateAttributePrefix names the boundary attributes generation writes and // the placeholder element the render option spells. UpdateAttributePrefix = pwruntime.UpdateAttributePrefix // UpdateGlobalName is the browser namespace api:client-update-api installs. UpdateGlobalName = pwruntime.UpdateGlobalName )
Update protocol names.
These are the framework's contracts with the runtime it ships to the browser — the header namespace, the attribute prefix, the installed name — and they are the shared leaf's, so both transports describe one document.
const ( LevelTrace = pwruntime.LevelTrace LevelDebug = pwruntime.LevelDebug LevelInfo = pwruntime.LevelInfo LevelWarn = pwruntime.LevelWarn LevelError = pwruntime.LevelError LevelOff = pwruntime.LevelOff )
Severities. Trace sits one step below debug, which slog does not name.
const ( StdoutFormatJSON = pwobservability.StdoutFormatJSON StdoutFormatPlaintext = pwobservability.StdoutFormatPlaintext )
Stdout record formats.
const ( QueryToggleAuto = pwobservability.QueryToggleAuto QueryToggleOn = pwobservability.QueryToggleOn QueryToggleOff = pwobservability.QueryToggleOff )
Diagnostic toggles. Auto ties the setting to something the process already knows, so a run that wants the ordinary answer configures nothing: query diagnostics read the runtime environment, and framework spans read whether anything exports them.
const ( // RateLimitBackendMemory counts inside this process, and is built in. RateLimitBackendMemory = pwratelimit.BackendMemory // RateLimitBackendRedis counts in a shared server. It needs the blank // import of ratelimitstore/redis. RateLimitBackendRedis = pwratelimit.BackendRedis )
Rate limit backend names a deployment selects with ratelimit.backend.
const ( SpanKindInternal = trace.SpanKindInternal SpanKindServer = trace.SpanKindServer SpanKindClient = trace.SpanKindClient SpanKindProducer = trace.SpanKindProducer SpanKindConsumer = trace.SpanKindConsumer )
Span kinds. The request root span is a server span; a call the application makes outward is a client span.
const ( StatusUnset = trace.StatusUnset StatusOK = trace.StatusOK StatusError = trace.StatusError )
Span status codes.
const ActionCallHeader = "Pw-Call"
ActionCallHeader says a server function was called by name from a script rather than reached by a gesture on an element.
It is a second axis rather than a second mode, because the mode already says what it says: this is an action request, and an update response applies to it exactly as it does to a submitted form. What this adds is who is holding the answer. A gesture has a document to update and nowhere to put a value; a script called this and can read one.
A header of this framework's own rather than the mode's parameter field: the module documents that field as the caller's wire version, and giving it a second meaning would collide the day a caller versions its wire.
const ActionSelectorField = tinybind.DefaultActionSelectorField
ActionSelectorField is the hidden field a lowered form carries to say which server function a native submit is for.
It is fixed rather than configured. The template compiler writes the field and the generated dispatcher reads it, and both take their name from the same place, so a project renaming one without the other would produce a form that submits to a dispatcher that cannot tell what it received.
const CSRFCookieName = pwruntime.CSRFCookieName
CSRFCookieName is the companion cookie the browser runtime reads a token from.
const DefaultEnv = pwconfig.DefaultEnv
DefaultEnv is used when EnvVar is unset or empty.
const DefaultRateLimitKeyPrefix = pwratelimit.DefaultKeyPrefix
DefaultRateLimitKeyPrefix namespaces the keys a shared counter store owns.
const EnvVar = pwconfig.EnvVar
EnvVar names the environment variable that selects the runtime environment.
const LiveManifestHeader = "Pw-Live-Manifest"
LiveManifestHeader carries the delivery validators a screen already holds, so a reconnect transfers what changed rather than everything.
It is the live namespace's counterpart to the update manifest and is a separate header for the same reason the modes are separate: boundary ids are positional and update instance ids are not, so one header carrying both would be two id spaces a parser has to tell apart by shape.
A hint and nothing more. The server executes the page either way, and a dropped, truncated, or wrong entry costs a delivery that was already going to be sent.
const LiveResponseMode = pwruntime.LiveResponseMode
LiveResponseMode is the token that selects a delivery stream.
const ReservedSignalPrefix = pwruntime.ReservedSignalPrefix
ReservedSignalPrefix is this framework's signal namespace. It and the check below are pwruntime's, so both transport runtimes reserve the same one: a namespace one backend guarded and the other did not would be reachable through the second.
const ResponseModeHeader = pwruntime.ResponseModeHeader
ResponseModeHeader names what one route writes. Absent, the route answers the document every bookmark, crawler, and cross-site link must receive; carrying the live token, it answers deliveries instead.
The mode is a header rather than a path or a query parameter because the page renders from its own URL: a token among the search parameters would reach template scope, and a second path would be a second route whose authorization and binding could drift from the one already generated and already tested. A custom header also cannot be set by a simple cross-origin form or link, which is the class of request policy:csrf-protection worries about.
const ScopeChainHeader = pwruntime.ScopeChainHeader
ScopeChainHeader carries the chain on a navigation delta.
Variables ¶
var ErrReservedSignalName = errors.New("pw: signal name uses the reserved " + ReservedSignalPrefix + " prefix")
ErrReservedSignalName reports a name inside this framework's namespace.
var ErrSignal = pwruntime.ErrSignal
ErrSignal matches any signal under errors.Is, for code that wants the classification without the value.
var ErrUpdateKeyMissing = errors.New("popcornweb: html.update.validator_key is required when html.update.enabled is true")
ErrUpdateKeyMissing reports updates enabled with nothing to key validators with.
var ErrUpdateKeyTooShort = errors.New("popcornweb: html.update.validator_key must carry at least 32 bytes of key material")
ErrUpdateKeyTooShort reports a validator key too small to key anything. A guessable key is equivalent to no key: anyone who can render the same page and guess it recomputes every digest, which is the attack the key exists to stop. The session keyring enforces the same 32-byte floor.
Functions ¶
func ActionSelector ¶
ActionSelector returns the server function selector a native form submit carried, or the empty string when it carried none.
The query is read before the body, because a submit button's formaction is what carries the selector when one form dispatches to several handlers, and that channel has to win over the form's own hidden field rather than merely coexist with it.
func AssembleOpenAPI ¶
func Authenticated ¶
Authenticated reports whether the request carries a verified identity.
func AuthenticatedContext ¶
AuthenticatedContext is Authenticated for code below the handler.
func ConfigContext ¶
ConfigContext is Config for code below the handler, which holds a context rather than the request.
func Context ¶
Context returns the request's context.Context.
It is the supported way to cross from the request handle to the currency the layers below a handler take. r.Context() yields the same value and is legal, but it names the net/http request type, which is what a second transport cannot follow; this call is rewritten instead.
func DB ¶
DB returns the pool of the effective connection group.
An engine that bypasses database/sql — PostgreSQL runs on its native pgx pool — has no *sql.DB, so DB reports false there. Generated SQL and Transaction are the portable surfaces; they run on either kind of pool. A raw statement that must run on both resolves the request executor through pwruntime.SQLExecutor and reads through sqlbind.Query, which dispatches to whichever cursor the connection provides.
func DBContext ¶
DBContext is DB for code below the handler, and for a caller holding a context SelectDB has pinned.
func DBDriverContext ¶
DBDriverContext is DBDriver for code below the handler.
func DeclaredLocales ¶
func DeclaredLocales() []string
DeclaredLocales returns the declared tags in declaration order, nil in a project that declared none.
func Development ¶
func Development() bool
Development reports whether the development relaxations apply.
An unset APP_ENV counts, because it resolves to development and running the framework with no environment set is what working on an application looks like. What does not count is any other named environment: the relaxations used to be refused by a list of the environments that must not have them — "stg", "prod", "production" — which meant "staging", "prd", "live", "uat" and every other spelling walked past a lock built to stop exactly them.
The cost of admitting the unset case is that a deployment which forgot the variable gets development behaviour. That is a real exposure — query records carry bind values there, and the session cookie may travel without Secure — so it is not silent: see EnvironmentDeclared and the startup warning it drives.
func DispatchAction ¶
func DispatchAction(w http.ResponseWriter, r *http.Request, handler http.HandlerFunc)
DispatchAction runs one server function on the page's own POST route and applies the post-redirect-get default.
A handler that writes nothing is answered with a redirect back to the page it was submitted from, so a reload does not resubmit and the address bar keeps showing the page. A handler that wrote a status, a header, or a body keeps exactly that response, which is what lets it redirect elsewhere, render the page inline with validation errors, or stream.
The redirect goes through Redirect rather than the module's own, which is the one thing this wrapper adds. The runtime posts an intercepted form to this same route, so the redirect a silent handler produces is commonly answered to a fetch — and a fetch follows a 303 and would apply a whole page where a region set belongs. Redirect already branches on that, so routing through it means a scriptless submit and an intercepted one reach the same handler and each gets the answer its own client can use.
func Env ¶
func Env() string
Env returns the resolved runtime environment token.
The value comes from APP_ENV and falls back to DefaultEnv. An invalid token resolves to DefaultEnv here and fails ParseConfig before requests are served.
func EnvironmentDeclared ¶
func EnvironmentDeclared() bool
EnvironmentDeclared reports whether APP_ENV named this process's environment, as opposed to the process defaulting to development because nothing set it.
It exists for the startup warning. Nothing decides a relaxation on it: the decision is Development, and this only says whether anyone asked for the answer that came back.
func IsBot ¶
IsBot reports whether the request came from a client that will not run the boundary runtime, so WriteHTMLChain should render the settled document rather than committing fallbacks it can never replace.
The answer comes from the User-Agent header alone. Nothing verifies it, which is acceptable precisely because the only thing it decides is which render branch runs: both branches render one chain with one set of data, so a forged header buys a slower first byte and nothing else. For the same reason this must never become an input to an access decision, and a handler must not use it to change what a page says — differing content by User-Agent is cloaking, while differing delivery for the same content is not.
func LocalePath ¶
LocalePath builds the URL of a path in a locale.
It is for URLs composed outside a template: a redirect Location, a mail body, a push deep link. Inside a template the locale is written with the framework's binding instead, per .knowledge decision:explicit-locale-in-links.
func LocalePathContext ¶
LocalePathContext is LocalePath for code below the handler — a mail body or a job payload composed after the response.
func Middlewares ¶
Middlewares performs framework initialization and returns the same wrapped handler stack used by Run. The startup summary is emitted here because the application owns the listener and the framework never learns its address.
func MovedPermanently ¶
MovedPermanently sends the browser to url with 301. Prefer PermanentRedirect unless a client you must serve predates it: 301 is ambiguous about the method in practice, where 308 is not.
func OpenAPIJSON ¶
func OpenAPIJSON(w http.ResponseWriter, r *http.Request)
func OpenSessionBackend ¶
func OpenSessionBackend(ctx context.Context, config SessionConfig, resources SessionResources) (session.Backend, error)
OpenSessionBackend opens the backend named by config.Backend.
func PackageAssetURL ¶
PackageAssetURL returns the absolute path a package asset is served at, and reports whether the package registered a file with that name.
A package never chooses its own URL: only the framework knows the reserved prefix, and only the bytes decide the digest. This is the lookup an application uses while a component cannot yet declare the asset it needs.
func ParseConfig ¶
func ParseConfig() error
ParseConfig loads every registered binding.
The load itself is pwconfig's; what this runtime adds is the two things around it, installed as hooks below: the framework subcommands come off the command line before configbind sees it, and the startup summary is captured from the result. Neither is a settings question, which is why neither moved.
func PathValue ¶
PathValue reads one path parameter the router stored when it matched.
It exists rather than a handler calling r.PathValue because that read is one no second transport can follow: fasthttp has no path routing of its own, so its path values come from whatever router ran and there is no method on the request to call. Routing both through the framework is what lets one generated decoder serve either.
func PermanentRedirect ¶
PermanentRedirect sends the browser to url with 308, keeping the method. It is the one to reach for when an address is retired.
func PrepareTestRuntime ¶
func PrepareTestRuntime(handler http.Handler, configs pwtestbridge.Configs, options pwtestbridge.Options) (pwtestbridge.Prepared, error)
PrepareTestRuntime builds an isolated runtime for testutil. Production code has no reference to it, so its database and reflection paths are dead code in an application binary.
func PublicAssetURL ¶
PublicAssetURL is the URL a document should name for one of the application's static assets, given its path inside the served tree.
A template calls this rather than writing a literal path, for the reason it calls RuntimeScriptURL rather than writing one: the URL a build serves an asset under carries a revision derived from that asset's own bytes, and only a URL nobody can hold across a change may be cached forever. A literal has no revision, so it revalidates on every load — correct, and one round trip per asset per page.
It answers for whichever transport is running, because the manifest it reads and the mount it resolves are both in the shared leaf.
func QueryLookup ¶
func QueryLookup(query QueryValues, key string) (string, bool)
QueryLookup reads one parameter from a parsed query, reporting whether it was present. Presence and emptiness are different answers: a flag parameter arrives with no value at all.
func QueryLookupAll ¶ added in v0.5.4
func QueryLookupAll(query QueryValues, key string) []string
QueryLookupAll reads every value of one repeated parameter, in URL order, which is the array spelling an urlencoded form submits for a checkbox group. It is the accessor a generated decoder reads a string[] input through.
func QueryValue ¶
QueryValue reads one query parameter, and reports whether it was present.
A handler binding its whole input takes api:request-binding instead. This is for the one-value case, where declaring a type costs more than it explains — and it exists so that case does not have to reach into the request itself, which is the read no second transport can follow.
func RateLimitStores ¶
func RateLimitStores() []string
RateLimitStores lists the registered backend names in order, which is what an error message reports when a configuration names one that is missing.
func Redirect ¶
Redirect sends the browser to another location.
It exists rather than leaving handlers on http.Redirect for two reasons, and only one of them is that a stdlib helper taking the writer and the request is a call no second transport can follow.
The other is the branch. An update request is a fetch, so a 303 is followed by the fetch and its target applied as a region set for the wrong page; the answer there is the navigate directive instead. That branch belongs in one place rather than in every action handler that redirects.
The target is refused unless a browser can follow it without running script. A redirect target is commonly a return path taken from the request, and the update runtime hands it to location.assign, which executes a javascript: URL rather than navigating to it. Refusing here means an application cannot turn its own redirect into script execution by forwarding a parameter it did not check — and the check is on both branches, because a handler should not have to know which one it took.
func RedirectSeeOther ¶
func RedirectSeeOther(w http.ResponseWriter, r *http.Request, url string)
RedirectSeeOther is the form an action handler wants: 303, so a reload does not repost what the handler just applied.
func Redraw ¶
func Redraw[P ReloadablePage](w http.ResponseWriter, r *http.Request, page func(P) HTMLFragment) bool
Redraw answers a redraw for what this page's markup can contain, and reports whether it did. A caller that gets true has had its whole response written.
It takes the page component, so the set comes from the template rather than from a list beside it:
func orders(w http.ResponseWriter, r *http.Request) {
if !mayView(r) { pw.WriteProblem(w, r, pw.Forbidden(nil)); return }
if pw.Redraw(w, r, templates.OrdersPage) { return }
// the query the page needs, which a redraw has now skipped
}
The component is named, not called, so nothing builds its parameters and the data behind them is never fetched. That is the point of answering here rather than inside the page render, where the same redraw costs the whole page's preparation.
A page whose markup reaches no reloadable component does not satisfy ReloadablePage and will not compile here. That is the honest answer: there is nothing on that page to redraw.
It belongs after the handler's own authorization. The address is the page's own URL, so the redraw already inherits what guards the page; placing the call below the checks is what extends that to the handler's own.
func RedrawComponents ¶
func RedrawComponents(w http.ResponseWriter, r *http.Request, components ...htmlupdate.Reloadable) bool
RedrawComponents answers a redraw for the components named here.
It is the escape hatch behind Redraw, for a handler that renders something other than a generated page component, or that publishes a narrower set than its template reaches. Prefer Redraw, which cannot fall out of step with the markup.
func RegisterConfig ¶
RegisterConfig registers one generated configbind target without parsing it.
func RegisterExtension ¶
func RegisterExtension(extension Extension)
RegisterExtension adds one extension to the framework chain. Imported packages call it from an init function so that only linked capabilities contribute configuration and code.
func RegisterHTMLDocument ¶
func RegisterHTMLDocument(wrapper HTMLWrapper)
RegisterHTMLDocument installs the generated application document shell. It is intended for generated templates/document_pw_gen.go code.
The state is pwruntime's rather than this package's, because the other transport runtime registers into the same place: generated registration is emitted per build with its import rewritten, and two registries would leave one build rendering pages with no document around them.
func RegisterHTMLErrorPage ¶
func RegisterHTMLErrorPage(resolve HTMLErrorPage)
RegisterHTMLErrorPage installs the application's error page resolver. It is intended for generated templates code and for an application that wants its own presentation; without one, a minimal built-in page is used.
func RegisterMiddleware ¶
func RegisterMiddleware(slot Slot, name string, middleware Middleware)
RegisterMiddleware adds one application middleware to the request chain at slot. A smaller slot runs earlier, so pw.SlotAccessLog - 5 observes the request ID and appears in the access log's timing, and pw.SlotGuard + 1 runs only for requests the guard admitted.
Call it from main, before Run or Middlewares builds the chain, exactly as RegisterSessionStore requires: the chain is composed once, and a middleware registered after that joins nothing.
The two fixed frames, SlotOperational and SlotAPIDoc, are handlers rather than middleware and refuse registration at their exact number; register one position to either side instead. A duplicate name and a nil middleware are each a panic at registration rather than a silent gap in the chain.
func RegisterPackage ¶
func RegisterPackage(pkg Package)
RegisterPackage adds one component package to the framework. Imported packages call it from an init function.
Registration is identity rather than activation: nothing a package registers reaches a request until the application mounts its assets, applies its stream, or calls its own Register.
func RegisterPageActions ¶
func RegisterPageActions(pattern string, actions ...PageAction)
RegisterPageActions publishes the actions reachable from one route.
The caller is a generated init beside the registry it reads, derived by pw generate the way the reloadable registration already is, so an application writes nothing and cannot leave the two out of step.
func RegisterRateLimitStore ¶
func RegisterRateLimitStore(name string, factory RateLimitStoreFactory)
RegisterRateLimitStore registers factory under name. A storage plugin calls it from init, so a blank import is what puts a backend in a binary:
import _ "github.com/shibukawa/popcornweb/ratelimitstore/redis"
The in-process counter is built in, because it adds no dependency and a limiter that needs one before it starts is one nobody switches on.
func RegisterReloadable ¶
func RegisterReloadable(components ...htmlupdate.Reloadable) error
RegisterReloadable publishes one generated component as a redraw endpoint.
A repeated kind is a startup error rather than a silent overwrite: the kind covers a component's name, parameters, and markup but not its package, so two identical templates in different packages produce the same one and the wrong component could answer.
The failure is also kept, because the ordinary caller is a generated init beside the component it registers. An init has nowhere to return an error to, and panicking there would end the process before any of the framework's logging exists to say which component collided, so startup reports it instead. A project registering by hand still gets it here and can decide for itself.
func RegisterSessionBackend ¶
func RegisterSessionBackend(name string, factory SessionBackendFactory)
RegisterSessionBackend registers factory under name. A storage plugin calls it from init, so a blank import is what puts a backend in a binary:
import _ "github.com/shibukawa/popcornweb/sessionstore/redis"
func RegisterSessionStore ¶
func RegisterSessionStore[T any](key string, placement session.Placement, options ...session.SlotOption)
RegisterSessionStore declares one piece of per-browser state, as a Go type with a placement, and is the only place either is stated.
pw.RegisterSessionStore[Cart]("cart", session.Private)
cart, ok := session.Load[Cart](ctx)
The placement states what the client may do with the value and where its bytes live: session.Shared is a plain cookie the front end reads and writes, session.ReadOnly a signed one it may read, session.Private is sealed and moves from a cookie to the configured backend at the login rotation, session.ServerOnly is sealed and always on the server because it must stay revocable, and session.RequestScope lives in process memory for one request and is never persisted. The deployment is left with one choice, which server backend session.backend names.
How long the value lives is the second, independent question. Stating nothing ties it to the session. session.ExpiresAfter ends it earlier, which is what a rotating secret or a short admission window wants. session.OutlivesSession exempts it from a sign-out, which is what a display language wants, and is available only to the two cookie-placed values because a record cannot outlive its own destruction.
Call it from main, after every package init has run, exactly as RegisterConfig requires: the declarations must be complete before the first request decodes anything.
func RegisterSubCommand ¶
RegisterSubCommand registers typed CLI-only input.
The registry is popcornweb/pwconfig's, because a subcommand is a fact about the command line rather than about a transport: an application that added one has it in both of its builds.
func ReservedSignalName ¶
ReservedSignalName reports a name this framework refuses to put on the wire. It is enforced where a signal is written rather than where one is constructed; pwruntime.ReservedSignalName carries why.
func Run ¶
Run owns parsing, framework initialization, serving, graceful shutdown, and resource cleanup.
func RunFrameworkAction ¶ added in v0.5.12
RunFrameworkAction handles config generation and probes after ParseConfig. Call it before opening application resources; return when handled is true.
func RuntimeScriptURL ¶
func RuntimeScriptURL() string
RuntimeScriptURL is the absolute path of the boundary runtime module. A document template names it through a declared external function rather than as a literal, so the template text survives an upgrade that moves the URL.
func ScaffoldEnv ¶
func ScaffoldTOML ¶
func ScalarUI ¶
ScalarUI serves a Scalar API reference page for the OpenAPI document at specURL. Assets load from a public CDN; nothing is embedded in the binary.
func SeeOther ¶
SeeOther sends the browser to url with 303, which fetches the target with GET whatever the request was, so a reload repeats nothing.
func SelectDB ¶
SelectDB pins a connection group, so generated SQL and Transaction run against that group instead of the default one:
CreateUser(pw.SelectDB(r, "writer"), options)
It returns a context rather than a request: pinning is a property of the value the layers below the handler carry, and those layers take a context.
An unknown group name fails at the first statement that uses the returned context, not here.
func SelectDBContext ¶
SelectDBContext is SelectDB for code below the handler, including a caller re-pinning a context it was given.
func SelectSessionDB ¶
SelectSessionDB pins the connection group holding the session table: session.rdb.group, falling back to the framework write group.
func SelectSessionDBContext ¶
SelectSessionDBContext is SelectSessionDB for code below the handler, which is where the framework's own session storage calls it.
func SelectWriteDB ¶
SelectWriteDB pins the connection group that framework-owned writes use: middleware.rdb.write_group, or the only group holding a writable connection.
A replica can never be selected this way, so a caller that must write does not have to know the deployment topology.
func SelectWriteDBContext ¶
SelectWriteDBContext is SelectWriteDB for code below the handler.
func SessionBackends ¶
func SessionBackends() []string
SessionBackends lists the registered backend names in order. It is what the startup summary and error messages report.
func SessionCookiePolicy ¶
func SessionCookiePolicy(config SessionConfig) (session.CookieOptions, error)
SessionCookiePolicy resolves the validated browser cookie policy of the session middleware. The cookie backend and the session manager share it, so both halves of a session travel under one policy.
func SessionKeyring ¶
func SessionKeyring(config SessionKeyringConfig) (*session.Keyring, error)
SessionKeyring reads the secret that protects everything the browser carries.
One secret serves both protections a slot can carry: session.ReadOnly signs and session.Private seals, and session.Keyring derives a purpose-separated subkey per mode. It is therefore required unless every declared slot is session.Shared, which protects nothing, or session.RequestScope, which never leaves process memory.
The secret itself never reaches an error message or a log.
func SessionManager ¶
SessionManager returns the manager the session middleware installed, or nil when session storage is disabled.
func SessionPrune ¶
SessionPrune returns the expiry sweep of the configured backend, or nil for a backend whose server or browser forgets records on its own.
func SessionRegistry ¶
SessionRegistry builds the registry of everything declared through RegisterSessionStore, plus the slots the caller adds.
The framework half of a login is one such slot, so plugin/auth passes its own declaration here rather than being privileged in storage.
func SetConfigLoadOptions ¶
func SetConfigLoadOptions(options configbind.LoadOptions)
SetConfigLoadOptions customizes configbind loading before ParseConfig.
func SetLocale ¶
func SetLocale(w http.ResponseWriter, locale Locale)
SetLocale records a reader's explicit language choice.
The framework owns the cookie and its validation; the control that offers the choice, and the action handler that calls this, stay with the application, on the same terms requirement:user-preference-rendering divides an override.
func SetOpenAPIInfo ¶
func SetOpenAPIInfo(info OpenAPIInfo) error
func SetRoute ¶
func SetRoute(w http.ResponseWriter, r *http.Request)
SetRoute records which route this response belongs to, so a metric is keyed by the pattern rather than by the path.
The framework calls it from every response writer it owns, so a generated page or API handler needs nothing. A hand-written handler that writes its own response and wants its metrics grouped calls it once, with the request the mux handed it.
It exists because the pattern cannot be read where the metric is recorded: net/http sets Request.Pattern on the copy the mux passes to the handler, and the frame that records the metric wraps the mux and never sees that copy. The value therefore travels back up on the response writer, which is the one thing the handler and the frame both hold.
A request that matched no pattern records no route, and never the raw path: an unbounded attribute is what the route attribute exists to avoid.
func SetSocketDefaults ¶
func SetSocketDefaults(opts SocketOptions)
SetSocketDefaults installs the process-wide socket options. It is shared with the other transport runtime, so installing them once covers both.
An origin check installed here replaces this framework's own resolution, on both runtimes and for every socket. Leave it unset to keep the resolution described on WebSocket.
func SetStreamErrorHandler ¶
func SetStreamErrorHandler(fn func(error))
SetStreamErrorHandler installs the destination for a stream failure raised after the response status has been sent. Passing nil discards them, which is the default: a runtime that logged on its own would be writing somewhere the application did not choose.
It is shared with the other transport runtime, so installing it once covers both.
func SnapshotTestConfigs ¶
func SnapshotTestConfigs() (pwtestbridge.Configs, error)
SnapshotTestConfigs copies the registered configuration for testutil. It is a direct call rather than an init-registered hook so a production binary that does not import testutil lets the linker discard this entire test seam.
func SpanIDContext ¶
SpanIDContext is SpanID for code below the handler, and reports the span that code is running in rather than the request root.
func SubCommand ¶
SubCommand is retained as a compatibility alias. Deprecated: use RegisterSubCommand.
func SwaggerUI ¶
SwaggerUI serves a Swagger UI page for the OpenAPI document at specURL. Assets load from a public CDN; nothing is embedded in the binary.
func TemporaryRedirect ¶
TemporaryRedirect sends the browser to url with 307, keeping the method.
func TraceID ¶
TraceID returns the request's trace ID, or an empty string outside a trace. It is the value to show a user on an error page so a report can be correlated.
func TraceIDContext ¶
TraceIDContext is TraceID for code below the handler.
func TracedContext ¶
TracedContext is Traced for code below the handler.
func Transaction ¶
Transaction runs fn inside a database transaction and passes it a context whose generated SQL functions use that transaction. A nested call opens a savepoint instead of a new transaction, so its failure rolls back only its own work and the outer transaction stays usable.
The transaction runs on the effective group of the request, which SelectDB pins for a transaction and for a single statement alike, and unpinned SQL inside it stays on that group rather than falling back to the default one:
pw.TransactionContext(pw.SelectDB(r, "writer"), func(ctx context.Context) error { ... })
func TransactionContext ¶
TransactionContext is Transaction for code below the handler, and for a caller holding a context pinned to a group.
func UpdateBuildID ¶
func UpdateBuildID() string
UpdateBuildID is the identity a rendered page carries and every update request is checked against, so a page from another build is answered with a complete document and a redraw from one is refused.
It is the effective value rather than the stamp: an unstamped binary has no vcs.revision, and the module's per-process identity stands in, which costs a complete document after a restart and never a wrong delta. Reading it is what a diagnostic and a test both need, since neither can derive it.
func WantsLive ¶
WantsLive reports whether this request asked for deliveries instead of a document, which is what a page renders differently for: the first answer of a live screen carries what a delivery will replace, and the document answer carries what a bookmark or a crawler must see.
It is exported for the same reason WantsUpdate is. The mode arrives in a header, and a page reading that header itself is a page the second transport cannot serve — fasthttp has no *http.Request to read it from. One predicate on both is what keeps a page portable.
func WantsUpdate ¶
WantsUpdate reports whether the caller can apply an update response.
It is the one branch point of an action handler. An ordinary form submission and a non-browser client cannot apply one, so they take the response the handler already wrote — a redirect, or JSON — and a page with the runtime takes the regions instead. Keeping it to one predicate is what stops the two paths from drifting apart.
func WantsValue ¶
WantsValue reports a server function called from a script.
It is the third branch of an action handler, beside WantsUpdate and the ordinary response:
switch {
case pw.WantsValue(r): // a script called it, so answer with a value
case pw.WantsUpdate(r): // an intercepted gesture, so answer with regions
default: // a native submit, so redirect
}
A handler that never asks is unchanged: it writes one response and every caller gets it, which is what a handler answering only regions already does.
func WebSocket ¶
func WebSocket[In, Out any](w http.ResponseWriter, r *http.Request, fn func(*Socket[In, Out]) error) error
WebSocket upgrades the request to a WebSocket, runs fn against a typed socket, and closes the socket when fn returns.
The two structs are the protocol: In is what the client sends and Out is what this handler answers with, and generation emits a decoder for the first and an encoder for the second from the types named in the callback. Neither has to be spelled at the call.
_ = pw.WebSocket(w, r, func(s *pw.Socket[ClientMsg, ServerMsg]) error {
for {
in, err := s.Read()
if err != nil {
return nil
}
if err := s.Write(ServerMsg{Type: "echo", Text: in.Text}); err != nil {
return err
}
}
})
The return value is the handshake error and nothing else. A non-nil value means the refusal response has already been written as a problem document, so the handler logs or counts it rather than answering. fn's own error is raised after the connection has been accepted, where no status is left to carry it, and reaches the handler installed with SetStreamErrorHandler instead — the same sink a stream failure takes, since the two have the same character.
The callback must not read w or r. It runs before this returns here and after the handler has returned on the other transport runtime, where the request value belongs to whichever request occupies that slot next. Capture what it needs — the identity, the peer — before calling.
A handshake from another origin is refused. The comparison is this deployment's own, reading the declared proxies and the declared trusted origins, so a socket behind a proxy is judged on the origin the browser actually used rather than on whatever the proxy put in Host. A request carrying no Origin at all is admitted: only a browser is required to send one, and refusing its absence would refuse every service and command-line client.
func WebSocketWith ¶
func WebSocketWith[In, Out any](w http.ResponseWriter, r *http.Request, opts SocketOptions, fn func(*Socket[In, Out]) error) error
WebSocketWith is WebSocket with per-call options, for the endpoint whose limits, cadence or origin policy differ from the process defaults.
func WithLogAttributes ¶
WithLogAttributes adds stable attributes to every record taken from the returned context, which is how middleware attaches request-scoped facts.
func WriteHTML ¶
func WriteHTML(w http.ResponseWriter, r *http.Request, leaf HTMLFragment)
WriteHTML renders one generated HTML fragment.
func WriteHTMLChain ¶
func WriteHTMLChain(w http.ResponseWriter, r *http.Request, wrappers []HTMLWrapper, leaf HTMLFragment, options ...HTMLOption)
WriteHTMLChain renders generated wrappers around one leaf without committing the response until TinyBind has validated and rendered the complete chain.
A chain that can open an await boundary streams instead: the shell and every fallback commit first, and each boundary is written as it settles. Nothing about the handler changes, because whether a response streams is a property of the templates it composed rather than a decision the handler makes.
A client that will not run the boundary runtime is the exception, and it needs no separate path: the buffered branch already blocks until every boundary settles, so classifying the client is enough to hand a crawler the finished document instead of the fallbacks it can never replace.
func WriteHTMLFragment ¶
func WriteHTMLFragment(w http.ResponseWriter, r *http.Request, fragment HTMLFragment)
WriteHTMLFragment renders one generated template as the whole response, with no document shell, no merged head, and no wrapper chain. It answers a partial request from an htmx-style swap library, whose target document already exists: composing the registered shell around the region would swap a second html, head, and body into the live page.
The response is always buffered. The streaming framing is only meaningful where the browser parser consumes the response as it arrives, and here the swap library holds the body and inserts it, so no marker the framework wrote could connect a completion to its placeholder. Blocking on await boundaries instead settles them in place and emits no placeholder at all, so a fragment carries no boundary id that could duplicate one still pending in the document it lands in, and needs no client runtime to be complete.
A fragment carrying head contributions is a programming error rather than a silent drop. A component's style block is scoped into the document head, so dropping it would swap in an unstyled region with nothing in any log; there is no head here to receive it, and inlining the tags would re-emit them on every swap with nothing owning or deduplicating them.
func WriteHTMLPage ¶
func WriteHTMLPage(w http.ResponseWriter, r *http.Request, wrappers []HTMLWrapper, leaf HTMLFragment, options ...HTMLOption)
WriteHTMLPage renders a page inside its own wrapper chain and the registered document shell, with the document outermost. It is intended for generated page tree code, which knows the ancestor layouts of a route but must not name the document: that one stays the framework's, exactly as it is for a handler calling WriteHTML.
func WriteProblem ¶
func WriteProblem(w http.ResponseWriter, r *http.Request, err error)
func WriteScaffoldEnv ¶
func WriteScaffoldTOML ¶
func WriteStatus ¶
WriteStatus is WriteAPI with the success status made explicit: 201 for a creation, 202 for an accepted job, 204 for no content — which writes no body. The status must be a literal or a named constant at the call site, because the generated OpenAPI document lists one response per static status the handler calls this with, and a status computed at runtime is one the scanner cannot see.
A 204 writes no body, which the library entry point already implements.
Unlike WriteAPI, this cannot answer a failure with a problem document. The status and the content type are written before the value is encoded, so every error it can return arrives after the response committed — a 204 writes no body and cannot fail at all — and a problem written over it would leave a 2xx carrying an error document. It is logged instead.
What reaches here is a type whose encoder generation never emitted, which means the call site never reached pw generate. That is a build mistake, and the log names it as one.
func WriteStream ¶
WriteStream negotiates a typed event stream, runs fn against it, and closes it.
The callback is the shape because it is the only one both transports can express. A backend that streams by registering a body writer runs that writer after the handler has returned, so a stream the handler opened and held has nowhere to live there. Moving this surface to the shape that transport requires is what lets one handler serve both.
It returns nothing, for the same reason. The callback runs after the handler returned on that backend, so an error cannot travel back to handler code; offering one here and not there would make the same source behave differently per transport, which is what the shared shape exists to prevent.
A failure to negotiate happens before anything is committed and becomes an ordinary problem response. Once the stream is open the status has been sent, so a failure from the callback reaches SetStreamErrorHandler instead. Close runs either way, which is what keeps the trailing bracket of the JSON array framing from depending on a caller remembering to write it.
func WriteUpdate ¶
func WriteUpdate(w http.ResponseWriter, r *http.Request, status int, regions ...UpdateRegion)
WriteUpdate answers a mutating request with the regions its action changed, so one round trip both performs the action and refreshes the page.
The status is the handler's own. The browser applies the regions whatever it says, because a rejected submission returns 4xx and the regions it carries are the validation errors — showing them is the point. That is the opposite of a redraw, where a non-2xx means the render failed.
func WriteUpdateNavigate ¶
func WriteUpdateNavigate(w http.ResponseWriter, r *http.Request, url string)
WriteUpdateNavigate tells the browser to leave the page, which is how an action that changed where the user belongs stays correct without guessing which regions to rewrite.
The target is refused unless it is one a browser can follow without running script. The value reaching here is commonly a return path taken from the request — the shape of a post-login redirect — and the browser runtime hands it to location.assign, which executes a javascript: URL rather than navigating to it. Refusing here means an application cannot turn its own redirect into script execution by forwarding a parameter it did not check.
Types ¶
type ActionDeclaration ¶
type ActionDeclaration = tinybind.Declaration
ActionDeclaration is what ServerAction returns. It carries nothing: the value exists only so the annotation can be written as a package-level declaration, which is where generation reads it.
func ServerAction ¶
func ServerAction(fn any, name ...string) ActionDeclaration
ServerAction declares that fn is a server action reachable from a component script, whatever its signature.
A handler-shaped function is an action by existing, because that shape is unambiguous. An arbitrary signature distinguishes nothing, since every function has one, so something outside the signature has to say which functions are actions. That is the whole of what this does.
Write it at package level, beside the function:
var _ = pw.ServerAction(GetUser)
func GetUser(ctx context.Context, id string) (User, error) { … }
A script reaches it as actions.getUser, the Go name in initialism-aware lowerCamelCase. Pass a name to override that: it is a wire name rather than a second identity, so a Go rename moves the address and leaves it where it is.
It is spelled here rather than left at the module's own because a page tree's templates, reserved paths and generated files are all this framework's, and a project should not import a second module to declare one.
type AsyncError ¶
type AsyncError = htmlbind.AsyncError
AsyncError is the presentation-safe failure a recover clause renders. The original Go error stays server-side and reaches the logger instead.
type Attribute ¶
Attribute is one scalar key-value pair. It is the same type a span attribute uses, so one value annotates a record and a span without conversion.
type Authentication ¶
type Authentication = pwruntime.Authentication
Authentication is the verified authentication result recorded by authentication middleware.
func RequestAuthentication ¶
func RequestAuthentication(r *http.Request) Authentication
RequestAuthentication returns the verified authentication result of the request. A request without authentication middleware, or an anonymous request, reports the explicitly unauthenticated zero value.
Authorization must consume this value, never the presence of a cookie.
func RequestAuthenticationContext ¶
func RequestAuthenticationContext(ctx context.Context) Authentication
RequestAuthenticationContext is RequestAuthentication for code below the handler.
type CSRFConfig ¶
type CSRFConfig = middlewares.CSRFConfig
CSRFConfig controls the synchronizer-token check on unsafe browser requests.
type CacheKey ¶
CacheKey is what a Memo key type implements: the type's identity followed by the framed encoding of every field marked with the cache tag.
It is tinybind's own interface, so a key method that generator emitted satisfies it directly. A hand-written key implements the same method and frames its fields with the cachekeybind helpers; nothing is re-exported here, because that package is stdlib-only and its helper set is wider than a copy here would stay in step with.
type CacheStore ¶
type CacheStore = pwruntime.CacheStore
CacheStore is a handle to one configured store, resolved by name.
func MemoStore ¶
func MemoStore(r *http.Request, name string) (*CacheStore, error)
MemoStore resolves a configured store by name.
A disabled cache section returns no store and no error, and every operation on a nil store falls through to its fetch, so a deployment removes caching without editing a call site. An unconfigured name is an error naming what is configured.
func MemoStoreContext ¶
func MemoStoreContext(ctx context.Context, name string) (*CacheStore, error)
MemoStoreContext is MemoStore for code below the handler, and for a resolution done once at startup rather than per request.
type CacheTagger ¶
type CacheTagger = pwruntime.CacheTagger
CacheTagger is the optional half of a key type, naming the tags whose invalidation drops the entry.
type Extension ¶
type Extension = pwextension.Extension
Extension is one imported framework capability. Setup runs once during framework initialization, after configuration parsing and database startup, and returns the middleware to install. Returning a nil middleware installs nothing, which is how a disabled extension opts out.
The registry lives in popcornweb/pwextension rather than here, so a plugin declaring a frame of this chain does not have to link this runtime to do it. A plugin that also serves the other transport would otherwise carry the whole net/http stack into a build that never calls any of it.
type FieldError ¶
type FieldError = pwruntime.FieldError
FieldError describes a single field-level validation failure.
func Field ¶
func Field(field, location, message string) FieldError
Field builds a field-level validation error for Validation.
type HSTSConfig ¶
type HSTSConfig = middlewares.HSTSConfig
HSTSConfig controls Strict-Transport-Security on verified HTTPS requests.
type HTMLCacheConfig ¶
type HTMLCacheConfig = pwconfig.HTMLCacheConfig
HTMLCacheConfig controls the output cache a component asks for with the template's cache annotation.
type HTMLConfig ¶
type HTMLConfig = pwconfig.HTMLConfig
HTMLConfig bounds and gates progressive HTML rendering.
type HTMLErrorPage ¶
type HTMLErrorPage = pwruntime.HTMLErrorPage
HTMLErrorPage resolves the fragment shown in place of a page whose rendering failed. It receives the mapped problem rather than the original error, so a template can never render a cause the server meant to keep.
It is declared in pwruntime for the reason the document shell is: generated registration reaches whichever runtime it imports, and the resolver names no transport, so one registration serves both.
type HTMLFragment ¶
HTMLFragment is a generated template with its parameters already bound.
type HTMLOption ¶
HTMLOption tunes one render. The framework supplies the options every response needs from HTMLConfig, so a caller passing one is extending that set rather than replacing it.
type HTMLUpdateConfig ¶
type HTMLUpdateConfig = pwconfig.HTMLUpdateConfig
HTMLUpdateConfig controls partial updates.
type HTMLWrapper ¶
HTMLWrapper is a generated template wrapper accepted by WriteHTMLChain.
type Lifecycle ¶
type Lifecycle = middlewares.Lifecycle
Lifecycle describes the deprecation and expected shutdown dates of the routes wrapped by LifecycleHeaders.
type Locale ¶
Locale identifies one locale the project declared in its i18n block.
It is the first argument of every generated message function, so the same function serves a request handler, a batch job, a mail renderer, and a push notification. There is no separate library mode: the generated surface already is one. See .knowledge api:locale-accessors.
func DefaultLocale ¶
func DefaultLocale() Locale
DefaultLocale returns the locale named by i18n.default_locale. It is the zero Locale in a project with no generated message package.
func LocaleContext ¶
LocaleContext returns the locale resolved for this request.
Resolution happens once, at routing, before the first byte. A template never calls this — a message reference reads the framework's implicit binding instead, which is what lets a cached component key on the locale without any rule about messages. See .knowledge data:locale-bindings.
func ParseLocale ¶
ParseLocale resolves a BCP 47 tag against the declared set by RFC 4647 lookup, so ja-JP finds ja. It reports absence rather than substituting the default.
This is the entry point for a locale that did not come from a request: a value read from a user record before sending mail, or from a job payload.
func RequestLocale ¶
RequestLocale is LocaleContext for a handler. It is not spelled Locale because that name is the locale type itself.
type LocaleChoice ¶
type LocaleChoice = pwruntime.LocaleChoice
LocaleChoice is one entry of a language switcher, and one alternate link.
func LocaleChoices ¶
func LocaleChoices(r *http.Request) []LocaleChoice
LocaleChoices reports the locales the current page is available in.
The switcher control, the hreflang alternates, and the canonical all read this one call, so a page cannot have them disagree. A mode with no per-locale URL reports entries whose URL is empty, because switching there is a server action rather than a link. See .knowledge requirement:locale-switching-surface.
type Log ¶
Log is the context-bound logger returned by Logger.
The accessor owns the name Logger, so the type carries the shorter one. Handler code normally writes pw.Logger(ctx).Info(...) and never names it.
func Logger ¶
Logger returns the logger bound to the request, its stable attributes, and the span active on ctx. It never returns something that cannot be called.
Acquire it again inside a child span to correlate records with that span:
ctx, span := pw.StartSpan(r, "load-user")
defer span.End()
pw.LoggerContext(ctx).Info("loaded", pw.Int("rows", n))
There is no Fatal or Panic. Logging reports what happened; it does not decide whether the process keeps running.
func LoggerContext ¶
LoggerContext is Logger for code below the handler, and for a caller holding a context a child span was opened on.
type MetricsConfig ¶
type MetricsConfig = pwconfig.MetricsConfig
MetricsConfig selects the instruments the framework records.
type Middleware ¶
type Middleware = pwextension.Middleware
Middleware is the standard net/http middleware shape used by framework extensions.
func LifecycleHeaders ¶
func LifecycleHeaders(lifecycle Lifecycle) (Middleware, error)
LifecycleHeaders returns middleware that announces an API resource's lifecycle using RFC 9745 Deprecation and RFC 8594 Sunset fields.
type MiddlewareConfig ¶
type MiddlewareConfig = pwconfig.MiddlewareConfig
MiddlewareConfig selects the framework's basic HTTP middleware.
type ObservabilityConfig ¶
type ObservabilityConfig = pwconfig.ObservabilityConfig
ObservabilityConfig controls runtime logging, tracing, and service identity.
type OpenAPIInfo ¶
type OpenAPIInfo = tinybind.OpenAPIInfo
type Option ¶
type Option func(*lifecycleOptions) error
Option configures framework lifecycle construction.
func WithDatabase ¶ added in v0.5.13
func WithDatabase(connections ...pwruntime.Connection) Option
WithDatabase supplies caller-owned connections instead of opening configured DSNs. RDB must remain enabled and its configured topology must be valid. Configure DefaultGroup when supplying multiple groups. Rebuilding the stack replaces the process set; shutdown leaves supplied pools open.
func WithExternalAssets ¶ added in v0.5.5
func WithExternalAssets(source middlewares.ExternalAssetSource) Option
WithExternalAssets reads the external public tree from a store instead of the directory beside the process, per requirement:cloudflare-r2-storage. The generated Cloudflare Workers entry passes the bucket binding here; a process host, which has the directory, passes nothing.
func WithPublicFS ¶
WithPublicFS supplies the embedded public tree, rooted at its public directory.
type OtelExportConfig ¶
type OtelExportConfig = pwconfig.OtelExportConfig
OtelExportConfig configures OTLP/HTTP export of traces and logs.
type Package ¶
type Package struct {
// Module is the Go module path. It is the identity everything else is keyed
// by, and it must match the package.module of the module's manifest so a
// declaration and a linked binary describe the same thing.
Module string
// Version is the module version the package was built at, supplied by the
// package as a constant. It is evidence for a compatibility report rather
// than a constraint: go.mod already performed the resolution.
Version string
// Assets holds embedded browser files, or nil. Their names, sizes, and hashes
// are cataloged once; requests then stream the selected file from this FS.
// Keeping the bytes embedded is what lets a TinyGo target serve them without
// an operating-system filesystem.
Assets fs.FS
// Migrations holds the package's own migration stream, or nil. The stream is
// applied before the application's, so a package's tables exist before
// anything the application writes can reference them.
Migrations fs.FS
// MigrationStem identifies the stream. It names the stream's version table
// and prefixes the package's own tables, which is how two packages are kept
// from claiming one name silently. It is required when Migrations is set.
MigrationStem string
}
Package is one linked component package. An imported package registers itself from an init function, so only a package the binary actually links contributes anything, exactly as an Extension does.
The value carries identity and bytes and nothing else. Behaviour a package contributes goes through the mechanisms that already exist: middleware and startup work through RegisterExtension, configuration through the generated configuration binding, and routes through an exported Register function the application calls on its own mux. Registration installs nothing that answers a request.
type PageAction ¶
type PageAction = pwruntime.PageAction
PageAction is one server function a page's component scripts may call.
type Pending ¶
Pending is one value a handler started before rendering and a template waits for in an await clause. A template parameter declared `async T` becomes a Pending[T] field in the generated Params struct.
A handler adopts progressive rendering by supplying these and changing nothing else: WriteHTML notices that the composed chain can open a boundary and streams on its own.
func Failed ¶
Failed returns a handle that has already settled to err. The boundary that awaits it renders its recover subtree.
func Go ¶
Go starts work in its own goroutine and returns the handle to pass as a template parameter. ctx bounds the work and stays the caller's to cancel; a render bounds only how long it waits.
A panic inside work becomes the handle's error, so a boundary reports it through its recover clause instead of taking the process down.
type Problem ¶
Problem is the application-facing RFC problem value.
It is declared in pwruntime and aliased here, so the value this package builds is the value the other transport runtime inspects and unwraps. A second declaration that agreed today would be a second chance to disagree later, and the failure would be a silent errors.As that stops matching.
func BadRequest ¶
The constructors are pwruntime's, re-exported so an application keeps naming them through pw and a rewritten call finds the same names on the other runtime.
func InternalServerError ¶
func PayloadTooLarge ¶
func RateLimited ¶
func ServiceUnavailable ¶
func TooManyRequests ¶
func Unauthorized ¶
func Validation ¶
func Validation(fields ...FieldError) Problem
Validation reports a 400 response carrying every detected field failure.
type PublicConfig ¶
type PublicConfig = middlewares.PublicAssetConfig
PublicConfig controls the framework-owned static asset endpoint.
type PublicError ¶
type PublicError = htmlbind.PublicError
PublicError is implemented by an error that supplies its own safe projection. Any other error reaches a recover clause as an internal code with no message, so error text cannot leak into a page by accident.
type QueryLogConfig ¶
type QueryLogConfig = pwconfig.QueryLogConfig
QueryLogConfig controls per-statement query logging.
type QueryValues ¶ added in v0.5.4
type QueryValues = tinybind.QueryValues
QueryValues is the request's query string split once into raw key=value spans, in wire order. It is the module's alias, so the value a decoder holds is the same type on either transport and the lookups cannot drift apart.
func Queries ¶
func Queries(r *http.Request) QueryValues
Queries returns the parsed query, for a decoder reading several parameters from one request.
Since system:tinybind v0.5.27 the parse is the module's own rather than url.Values: the two transports used to split the same raw query with two parsers — url.ParseQuery here, the driver's on fasthttp — and a pair one of them drops, a semicolon or a broken percent escape, then bound different values for a query the client chose. One parser is what makes the answer one.
type RDBConnectionConfig ¶
type RDBConnectionConfig = pwconfig.RDBConnectionConfig
RDBConnectionConfig is one pool of the connection set.
type RateLimit ¶
RateLimit describes the compatibility quota fields and standard retry hint emitted by RateLimited.
type RateLimitConfig ¶
type RateLimitConfig = middlewares.RateLimitConfig
RateLimitConfig bounds how often one caller, and the process as a whole, may arrive within a window. It is its own binding rather than a member of SecurityConfig, because a backend selection carrying a DSN does not belong beside a list of response headers.
type RateLimitCounter ¶
type RateLimitCounter = pwratelimit.Counter
RateLimitCounter is the storage a limiter counts in: add one to the count under a key for a window, and report the new total.
type RateLimitRedisConfig ¶
type RateLimitRedisConfig = middlewares.RateLimitRedisConfig
RateLimitRedisConfig addresses the shared counter server.
type RateLimitStoreFactory ¶
type RateLimitStoreFactory = pwratelimit.StoreFactory
RateLimitStoreFactory opens the counter store a configuration selects. The returned close runs during shutdown and may be nil.
type ReloadablePage ¶
type ReloadablePage interface {
PwReloadables() []htmlupdate.Reloadable
}
Redraw answers a redraw request for the components named here, and reports whether it did. A caller that gets true has had its whole response written.
It belongs at the top of a handler, after that handler's own authorization:
func orders(w http.ResponseWriter, r *http.Request) {
if !mayView(r) { pw.WriteProblem(w, r, pw.Forbidden(nil)); return }
if pw.Redraw(w, r, templates.OrderRowReloadable) { return }
// ordinary page render
}
The address is the page's own URL, which is the whole reason this is a call rather than an endpoint. Path protection is configured by path pattern, so a redraw on a reserved path needs a second pattern kept in step with the one protecting the page the component sits on — two rules that must agree with nothing forcing them to. Here the redraw is the same request as the page, so it inherits the page's protection, and placed after the handler's own checks it inherits those too rather than only the middleware's.
Naming the components is what bounds the surface: this handler answers for these and nothing else, so a page cannot be asked to render a component it never shows. That set is readable in Go beside the check that guards it.
It stays the caller's job to authorize the arguments. Every parameter but the instance id arrives from whoever issued the request, so a component that loads a record by identifier verifies ownership itself exactly as a handler does. ReloadablePage is implemented by a generated component's parameter struct when that component's markup can contain a reloadable one.
Nobody writes it. Generation folds each component's call graph and emits the method on the components it reaches something from, which is what lets Redraw take the page itself rather than a list the author has to keep in step with the template.
type SecurityConfig ¶
type SecurityConfig = pwconfig.SecurityConfig
SecurityConfig controls framework request and response security policy.
type SecurityHeadersConfig ¶
type SecurityHeadersConfig = middlewares.SecurityHeadersConfig
SecurityHeadersConfig controls browser-facing response headers.
type ServerConfig ¶
type ServerConfig = pwconfig.ServerConfig
ServerConfig controls the primary HTTP listener and operational endpoints.
type SessionBackendFactory ¶
type SessionBackendFactory = pwsession.BackendFactory
SessionBackendFactory opens one storage backend from configuration.
type SessionConfig ¶
type SessionConfig = sessionconfig.SessionConfig
The session binding. Every type is a true alias of the one declared in sessionconfig, so pw and popcornweb/plugin/auth name one type from two packages without depending on each other, and the reflect.Type keyed configuration registry resolves both names to one entry.
type SessionCookieConfig ¶
type SessionCookieConfig = sessionconfig.SessionCookieConfig
The session binding. Every type is a true alias of the one declared in sessionconfig, so pw and popcornweb/plugin/auth name one type from two packages without depending on each other, and the reflect.Type keyed configuration registry resolves both names to one entry.
type SessionCookieStoreConfig ¶
type SessionCookieStoreConfig = sessionconfig.SessionCookieStoreConfig
The session binding. Every type is a true alias of the one declared in sessionconfig, so pw and popcornweb/plugin/auth name one type from two packages without depending on each other, and the reflect.Type keyed configuration registry resolves both names to one entry.
type SessionDynamoConfig ¶
type SessionDynamoConfig = sessionconfig.SessionDynamoConfig
The session binding. Every type is a true alias of the one declared in sessionconfig, so pw and popcornweb/plugin/auth name one type from two packages without depending on each other, and the reflect.Type keyed configuration registry resolves both names to one entry.
type SessionKeyringConfig ¶
type SessionKeyringConfig = sessionconfig.SessionKeyringConfig
The session binding. Every type is a true alias of the one declared in sessionconfig, so pw and popcornweb/plugin/auth name one type from two packages without depending on each other, and the reflect.Type keyed configuration registry resolves both names to one entry.
type SessionRDBConfig ¶
type SessionRDBConfig = sessionconfig.SessionRDBConfig
The session binding. Every type is a true alias of the one declared in sessionconfig, so pw and popcornweb/plugin/auth name one type from two packages without depending on each other, and the reflect.Type keyed configuration registry resolves both names to one entry.
type SessionRedisConfig ¶
type SessionRedisConfig = sessionconfig.SessionRedisConfig
The session binding. Every type is a true alias of the one declared in sessionconfig, so pw and popcornweb/plugin/auth name one type from two packages without depending on each other, and the reflect.Type keyed configuration registry resolves both names to one entry.
type SessionResources ¶
SessionResources are the framework resources a session backend may borrow. A backend closes nothing it finds here: what it did not open, it does not own.
type Signal ¶
Signal is one named instruction and its encoded payload.
func AsSignal ¶
AsSignal reports whether err is a signal, and returns it. It is what the live loop classifies with, and it is exported because an application wrapping a source of its own needs the same test.
func NamedSignal ¶
NamedSignal builds a signal with no payload.
func NewRawSignal ¶
NewRawSignal builds a signal from a payload that is already encoded JSON.
Nothing validates those bytes. A caller passing something that is not one JSON value produces a record a client cannot parse, which is why NewSignal is the ordinary path.
func NewSignal ¶
func NewSignal[T SignalPayload](name string, payload T) Signal
NewSignal builds a signal carrying an encoded payload.
The payload is encoded here, at the call site, so the value is immutable once yielded and the runtime holds bytes rather than something it would have to reflect on to write. A nil payload is legal and means an instruction with no arguments.
type SignalPayload ¶
type SignalPayload = pwruntime.SignalPayload
SignalPayload is what a signal carries. Generated encoders satisfy it, which is what keeps a payload encoded by the same codec as every other typed value this framework sends.
type Slot ¶
Slot orders every frame of the request chain, and the numbers are the shared leaf's so both runtimes compose in one order.
Framework frames sit at multiples of ten, BASIC style, so a middleware can be inserted between any two by picking a number in the gap: pw.SlotAccessLog - 5 runs after the request ID is minted and before the access log times the request.
type Socket ¶
Socket is an open typed WebSocket connection. It is the module's own type rather than a wrapper around it, for the reason Stream is: the value a callback receives here is the value it receives on the other transport runtime, so a handler body is the same text on both.
Read decodes one message into In and Write encodes one from Out, each through a generated codec. Read must be called from one goroutine; Write may be called from any, which is what makes a broadcast goroutine safe.
type SocketOptions ¶
type SocketOptions = tinybind.SocketOptions
SocketOptions configures one socket: the read limit, the idle and write deadlines, the ping cadence, the offered subprotocols, and the origin check. A zero field takes the process default, and a process default left unset takes a concrete value — nothing reaches the connection as zero, because an unset read deadline is a read nothing can interrupt.
func SocketDefaults ¶
func SocketDefaults() SocketOptions
SocketDefaults returns the effective process defaults, with every unset field resolved to the value it will actually be served with.
type Span ¶
Span is one unit of traced work. Always end it, normally with defer.
func StartSpan ¶
StartSpan opens a child of the request's active span and returns a context carrying it. Outside a trace, or with tracing disabled, it returns a span that records nothing and costs nothing to end.
ctx, span := pw.StartSpan(r, "load-user", pw.String("db.system.name", "sqlite"))
defer span.End()
The request root span is created by the framework, so a handler starts only the spans that describe its own work. Work below the handler already holds the context this returned, and nests through StartSpanContext.
func StartSpanContext ¶
func StartSpanContext(ctx context.Context, name string, attributes ...Attribute) (context.Context, *Span)
StartSpanContext is StartSpan for code below the handler, which nests its own span under the one it was given.
type Stream ¶
Stream is an open typed event stream. It is the module's own type rather than a wrapper around it, so the value a callback receives here is the value it receives on the other transport runtime, and a handler body is the same text on both.
Write sends one value. Close is the runtime's, not the caller's: the entry below runs it whichever way the callback ends.
type TraceConfig ¶
type TraceConfig = pwconfig.TraceConfig
TraceConfig selects the spans the framework opens inside a request.
type UnsetPendingError ¶
type UnsetPendingError = htmlbind.UnsetPendingError
UnsetPendingError reports a required async value the handler never set. It is raised before any byte commits, so it becomes an ordinary problem response.
type UpdateRegion ¶
type UpdateRegion = htmlupdate.Update
UpdateRegion pairs a target element id with the fragment replacing it.
func Replace ¶
func Replace(targetID string, fragment HTMLFragment) UpdateRegion
Replace names one region an action response rewrites. The rendered root element must carry the same id, or the region becomes unaddressable after the first update.
Source Files
¶
- action.go
- apidoc.go
- async.go
- bind.go
- bootlog.go
- bootlog_attended.go
- botdetect.go
- cache.go
- config.go
- context.go
- csrf.go
- database.go
- devannounce_mode.go
- devdata_mode.go
- devtest_mode.go
- environment.go
- extension.go
- hostrefusal.go
- hostrefusal_attended.go
- htmlerror.go
- htmlruntime.go
- htmlruntime_mode.go
- htmlupdate.go
- lifecycle.go
- lifecycleheaders.go
- listen.go
- live.go
- locale.go
- log.go
- middleware_runtime.go
- mux.go
- observability.go
- observedmetrics.go
- openapi.go
- package.go
- packageassets.go
- pageactions.go
- publicassets.go
- ratelimit.go
- ratelimitstore.go
- redirect.go
- rendercache.go
- rendertrace.go
- response.go
- response_coding.go
- response_gzip_std.go
- response_zstd_std.go
- route.go
- scaffold.go
- scopechain.go
- scriptless.go
- sessionextension.go
- signal.go
- signal_std.go
- stream.go
- subcommand.go
- test_bridge.go
- toolmode.go
- trace.go
- validation.go
- version_std.go
- websocket.go