pwfast

package
v0.5.13 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 47 Imported by: 0

Documentation

Overview

Package pwfast is the pw surface over a fasthttp request, for the build that decision:transport-source-transform generates.

It is the second half of a pair. An application author writes net/http and calls pw; generation rewrites those handlers for the other transport and imports this package under the name pw, so a rewritten call selector is unchanged and only the import line moves. Every declaration here therefore carries the same name as its pw counterpart, takes the request value first, and keeps the parameter names the net/http half uses — which is what makes a rewritten body the same text on both transports rather than a translation of it.

Not tagged

This package carries no build constraint, deliberately. Only application files are tagged; a library behind a tag is invisible to go vet, go test and gopls in an untagged run, and both surfaces are worth covering in one.

Shared state, not a second copy

The document shell, the error page, the reloadable components, the problem value and the resolved update configuration all live in pwruntime, and both runtimes reach that one copy. This is not tidiness: generated registration runs from init and calls whichever package it imports, so two registries would leave one build rendering pages with no document around them and answering no redraw at all.

The update configuration travels the same way. Whichever runtime read the configuration file publishes what it resolved, and this half reads it — a settings file is not a transport concern, and this package has no reader of its own.

Streaming

ServeUpdate answers a streamed navigation. It calls the same module entry the net/http half calls, so the two transports send the same records from one implementation rather than two that agree.

ServeLive holds a live subscription open. Every decision it makes — the admission bound, the watchdog, the digest suppression seeded from the client's manifest, the record framing, the close reasons — is pwruntime's, and the net/http half now reads the same ones. A first cut called the module's live entry instead and was withdrawn: that entry has none of those, so it would have served a poorer stream here than there with nothing to report the difference.

One thing genuinely differs. The body writer runs after the handler has returned, so nothing may be read from the request value inside the loop and the render is bounded by the watchdog rather than by the request context. A client that goes away is noticed on the next write, which is the signal the other half falls back to once a record fails.

Nothing that is missing is stubbed. A declaration that compiled and did nothing would hide a gap where an absent one is a build error naming the symbol, which is what the refusal contract does everywhere else.

Index

Constants

View Source
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
	SlotSession          = pwruntime.SlotSession
	SlotAuthentication   = pwruntime.SlotAuthentication
	SlotRateLimit        = pwruntime.SlotRateLimit
	SlotCSRF             = pwruntime.SlotCSRF
	SlotGuard            = pwruntime.SlotGuard
	SlotAPIDoc           = pwruntime.SlotAPIDoc
)
View Source
const (
	LevelTrace = pwruntime.LevelTrace
	LevelDebug = pwruntime.LevelDebug
	LevelInfo  = pwruntime.LevelInfo
	LevelWarn  = pwruntime.LevelWarn
	LevelError = pwruntime.LevelError
	LevelOff   = pwruntime.LevelOff
)
View Source
const ActionCallHeader = "Pw-Call"

ActionCallHeader says a server function was called by name from a script rather than reached by a gesture, matching the net/http half so one document drives either backend.

ActionSelectorField is the hidden field a lowered form carries to say which server function a native submit is for. It matches the net/http half, so one generated form works on either backend.

View Source
const CSRFSecretSlot = middlewares.CSRFSecretSlot

CSRFSecretSlot is the registration key of that slot.

View Source
const LiveManifestHeader = "Pw-Live-Manifest"

LiveManifestHeader carries what each boundary on the client is showing, so a reconnect re-sends only what changed.

View Source
const LiveResponseMode = "live"

LiveResponseMode is the token that selects a delivery stream.

View Source
const ResponseModeHeader = "Pw-Response-Mode"

ResponseModeHeader selects deliveries over a document, and LiveResponseMode is the token that does it. They are declared here rather than imported from the other half for the reason LiveManifestHeader is: the two transports share a wire, not a package.

Variables

This section is empty.

Functions

func ActionSelector

func ActionSelector(r *fasthttp.RequestCtx, field string) string

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.

func Authenticated

func Authenticated(ctx context.Context) bool

Authenticated reports whether the request carries a verified identity.

func AuthenticatedContext

func AuthenticatedContext(ctx context.Context) bool

AuthenticatedContext is Authenticated for code below the handler.

func Chain

func Chain(handler fasthttp.RequestHandler, middleware ...Middleware) fasthttp.RequestHandler

Chain wraps handler in the given middleware, outermost first.

The order is the reading order: Chain(h, a, b) runs a, then b, then h. That is the order pw.Slot numbers describe, so a chain assembled from the same list on either transport runs in the same order.

func ClientAddress

func ClientAddress(ctx context.Context) string

ClientAddress returns the caller the chain resolved, which is what every downstream bound counts against.

It takes no request beside the context, unlike the other half's reader. That one falls back to the peer address when no frame recorded one, because a net/http handler can be reached without the chain around it; here the request value is the context, so a missing value means the frame did not run and saying so is better than substituting the peer, which is the proxy whenever there is one.

func Compose

func Compose(handler fasthttp.RequestHandler, frames ...Frame) fasthttp.RequestHandler

Compose wraps handler in frames, outermost first by slot, through the shared ordering rule.

func Config

func Config[T any](ctx context.Context) T

Config returns the resolved configuration for T.

It is the same two-step answer the other half gives, from the same shared resolution: whatever a middleware recorded on this request, and otherwise the process-wide parsed value.

The parameter is a context rather than the request because this transport's request value is one. That is the property that made the request-scoped accessors portable at all — a handler passing r where a context is wanted compiles unchanged on both sides — so these entries take ctx and a rewritten call needs no argument moved.

Nothing here parses a configuration file. This half binds none, so what it reads is what the runtime that did the binding published. A build with no such runtime in it reads zero values, which is the honest answer rather than a guess: no file was read, so no setting was chosen.

func ConfigContext

func ConfigContext[T any](ctx context.Context) T

ConfigContext is Config for code below the handler.

func Context

func Context(ctx context.Context) context.Context

Context returns the request's context.Context, which on this transport is the request value itself.

func DB

func DB(ctx context.Context) (*sql.DB, bool)

DB returns the pool of the effective connection group.

func DBContext

func DBContext(ctx context.Context) (*sql.DB, bool)

DBContext is DB for code below the handler.

func DBDriver

func DBDriver(ctx context.Context) (string, bool)

DBDriver reports the driver scheme of the effective framework database pool.

func DBDriverContext

func DBDriverContext(ctx context.Context) (string, bool)

DBDriverContext is DBDriver for code below the handler.

func DispatchAction

func DispatchAction(r *fasthttp.RequestCtx, handler func(*fasthttp.RequestCtx))

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; one that wrote a status, a header, or a body keeps exactly that response.

The redirect goes through Redirect rather than the module's own, for the reason the net/http half gives: the runtime posts an intercepted form to this same route, so a silent handler's redirect is commonly answered to a fetch, which would follow a 303 and apply a whole page where a region set belongs.

The observation compares the response before and after rather than wrapping a writer, because this transport carries the request and the response in one value and there is nothing to wrap.

func FormValue

func FormValue(r *fasthttp.RequestCtx, key string) string

FormValue reads one submitted form field, on the same terms as QueryValue.

func IsBot

func IsBot(r *fasthttp.RequestCtx) bool

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 verdict comes from the shared classifier over the shared token list, so this half and the other reach the same answer about the same crawler. What differs is only where the two values it consults come from: the net/http half reads the configuration off the request context, and this one reads what that half published, because no configuration is bound on this transport yet.

func ListenAndServe

func ListenAndServe(ctx context.Context, address string, handler fasthttp.RequestHandler, options RuntimeOptions) error

ListenAndServe builds the chain, binds address, and serves until ctx is cancelled.

It owns the port and nothing else. Startup — parsing the configuration, opening the pool, building the session manager — belongs to whichever runtime does it, and a caller that wants this transport to do all of it calls Run instead. This is the entry for a caller that has already done startup its own way, which is what a test and an embedding application both need.

func LocaleChoices

func LocaleChoices(r *fasthttp.RequestCtx) []pwruntime.LocaleChoice

LocaleChoices reports the locales the current page is available in, for a language switcher and for the alternate links.

It is the fasthttp half of the same entry the net/http build has. The switcher data is the same on both transports because it is derived from the declared locale set, the route's mode, and this request's path — none of which is a property of the runtime that served it.

func LocalePath

func LocalePath(ctx context.Context, locale Locale, path string) string

LocalePath builds the URL of a path in a locale.

func LocalePathContext

func LocalePathContext(ctx context.Context, locale Locale, path string) string

LocalePathContext is LocalePath for code below the handler.

func Logger

func Logger(ctx context.Context) pwruntime.Logger

Logger returns the request's logger, or the process default.

func LoggerContext

func LoggerContext(ctx context.Context) pwruntime.Logger

LoggerContext is Logger for code below the handler.

func Middlewares

func Middlewares(handler fasthttp.RequestHandler, options RuntimeOptions) (fasthttp.RequestHandler, error)

Middlewares builds the framework chain around handler.

It is the second transport's counterpart to pw.Middlewares, and it is deliberately smaller than that one. The other builds the whole chain and also performs framework initialization — configuration parsing, database startup, observability, the validations that must fail before a port is bound. None of that is transport-shaped and none of it is duplicated here: a deployment runs it once, on whichever runtime owns startup, and what this assembles is the request path.

The authentication frames

They are not here, and their absence is now a choice rather than a gap. popcornweb/plugin/auth/authfast supplies them, as frames positioned by their own slots and a guard policy this takes as an argument, because there is no extension registry on this transport: an imported capability cannot install a frame here, and every frame this chain gains from a plugin is one the application named.

What the application registers for itself is the exception, and a deliberate one: RegisterMiddleware writes into a process list this reads, so the registration reads the same on both builds. The frame is still one the application's own source names — its main called the function — which is the property the argument-assembled chain was protecting.

What is still absent is absent rather than stubbed, so a build that needs one fails to name it rather than serving requests with a frame that silently does nothing — which for a guard would be an authorization check that looks installed.

func NetHTTPHandler

func NetHTTPHandler(handler fasthttp.RequestHandler) http.Handler

NetHTTPHandler exposes a fasthttp handler through net/http. Source-function runtimes own a net/http listener and cannot accept RequestHandler directly; an in-memory HTTP/1 connection preserves the wire contract without teaching either runtime about the other's request structures.

func NewCarrier

func NewCarrier(r *fasthttp.RequestCtx) session.Carrier

NewCarrier wraps a request value as a session carrier.

func OpenAPIJSON

func OpenAPIJSON(r *fasthttp.RequestCtx)

OpenAPIJSON serves the assembled document.

It reassembles per request where the net/http half is served from the module's cache, because that cache is keyed on a registration counter the module does not export and there is no way to observe an invalidation from out here. The endpoint is a documentation route rather than a hot one, so the cost buys correctness against a fragment registered after the first read.

func Parse

func Parse[T any](r *fasthttp.RequestCtx) (T, error)

Parse binds the request into the generated input type.

func PathValue

func PathValue(r *fasthttp.RequestCtx, key string) string

PathValue reads one path parameter, which the router stored when it matched.

It is here rather than being a method on the request value because this transport has no path routing of its own: the value comes from whatever router ran, and a generated decoder calling one function works with any of them. The net/http half has the same entry for the same reason.

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

func QueryValue(r *fasthttp.RequestCtx, key string) (string, bool)

QueryValue reads one query parameter, and reports whether it was present.

A handler binding its whole input takes Parse 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.

func Redirect

func Redirect(r *fasthttp.RequestCtx, url string, status int)

Redirect sends the browser to another location.

It branches the way the net/http half does, and the branch is the reason it exists rather than a redirect helper being unportable. 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.

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.

func RedirectSeeOther

func RedirectSeeOther(r *fasthttp.RequestCtx, 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(r *fasthttp.RequestCtx) bool

Redraw answers a redraw from the process-wide published set, which is what a generated page route calls after its own Load has run.

func RedrawComponents

func RedrawComponents(r *fasthttp.RequestCtx, components ...pwruntime.UpdateReloadable) bool

RedrawComponents 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: a redraw reaches the component through the same route, so whatever guards the page guards the region.

func RegisterHTMLDocument

func RegisterHTMLDocument(wrapper HTMLWrapper)

RegisterHTMLDocument and RegisterHTMLErrorPage reach the same state pw's do, which is the whole reason that state is in pwruntime: generated registration calls whichever package it imports, and both must find one registry.

func RegisterHTMLErrorPage

func RegisterHTMLErrorPage(resolve pwruntime.HTMLErrorPage)

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 SlotAccessLog - 5 observes the request ID and appears in the access log's timing, and SlotGuard + 1 runs only for requests the guard admitted.

It is pw.RegisterMiddleware with one word changed, and that is the point. The middleware body is written per transport — decision:backend-specific-middleware settles why, and the signature here says it plainly — so the registration is the one part of the arrangement that had no reason to differ, and a project building both ways should find its two mains differing only in the body.

Call it from main, before Run, Start or Middlewares composes the chain, exactly as RegisterSessionStore requires: the chain is composed once, and a middleware registered after that joins nothing. A serverless build registers in the same place, because main runs as far as its Run call before the generated wrapper captures it.

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 — the same three refusals the other build makes, so one rule covers both.

This is the application's seam and not a plugin's. An imported capability still hands this transport a frame through RuntimeOptions.Extra, where the application names it: a plugin registering from an init would be a frame in the chain that nothing in the application's source mentions.

func RegisterReloadable

func RegisterReloadable(components ...pwruntime.UpdateReloadable) error

RegisterReloadable publishes generated components as redraw endpoints, reaching the one registry decision:shared-runtime-leaf keeps.

func Run

func Run(ctx context.Context, handler fasthttp.RequestHandler, option ...Option) error

Run owns parsing, framework initialization, serving, graceful shutdown and resource cleanup.

It is what a generated entry point calls, and the second transport's counterpart to pw.Run. The listener is bound here rather than inside Serve so that the startup line reports the port that was actually accepted — which is the one an operator opens when the configuration asked for port 0.

func RunFrameworkAction added in v0.5.12

func RunFrameworkAction() (handled bool, err error)

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 SelectDB

func SelectDB(ctx context.Context, group string) context.Context

SelectDB pins a connection group onto the context generated SQL takes.

func SelectDBContext

func SelectDBContext(ctx context.Context, group string) context.Context

SelectDBContext is SelectDB for code below the handler.

func SelectSessionDB

func SelectSessionDB(ctx context.Context) (context.Context, error)

SelectSessionDB pins the connection group holding the session table.

func SelectSessionDBContext

func SelectSessionDBContext(ctx context.Context) (context.Context, error)

SelectSessionDBContext is SelectSessionDB for code below the handler.

func SelectWriteDB

func SelectWriteDB(ctx context.Context) (context.Context, error)

SelectWriteDB pins the connection group framework-owned writes use.

func SelectWriteDBContext

func SelectWriteDBContext(ctx context.Context) (context.Context, error)

SelectWriteDBContext is SelectWriteDB for code below the handler.

func Serve

func Serve(ctx context.Context, listener net.Listener, handler fasthttp.RequestHandler) error

Serve runs an already-built handler on a listener the caller owns, which is what a test and an application embedding this framework both need.

func ServeLive

func ServeLive(r *fasthttp.RequestCtx, wrappers []HTMLWrapper, leaf HTMLFragment, options ...HTMLOption) bool

ServeLive answers a live mode request with the deliveries of one chain, and reports whether it did.

Every decision it makes is pwruntime's: the admission bound, the watchdog, the digest suppression seeded from the client's manifest, the record framing and the close reasons. What is written here is the transport — obtaining a writer that flushes, and reading the two request values the loop needs — so the two runtimes cannot disagree about the wire.

The body writer runs after the handler has returned, which is this transport's whole shape, and it changes one thing the other half relies on: the request value is pooled and gone by then, so nothing may be read from it inside the loop and the render is bounded by the watchdog rather than by the request context. A client that goes away is noticed on the next write, which is the same signal the other half falls back to once a record fails.

func ServeUpdate

func ServeUpdate(r *fasthttp.RequestCtx, wrappers []HTMLWrapper, leaf HTMLFragment, options ...HTMLOption) bool

ServeUpdate answers a negotiated streamed navigation with the delta of one chain, and reports whether it did.

The module owns the comparison and the framing; what this supplies is the headers a stream must carry before its first record, and the request value it writes into. Both come from the same entry pw calls, so the two transports send the same records rather than two implementations that agree.

func SetLocale

func SetLocale(r *fasthttp.RequestCtx, locale pwruntime.Locale)

SetLocale records a reader's explicit language choice.

The value is validated against the declared set before it is written, because the cookie is client-writable and a decoded value is request input.

func SetRoute

func SetRoute(r *fasthttp.RequestCtx)

SetRoute is the counterpart of pw.SetRoute, collapsed to this transport's one argument, and it has nothing to do.

The route is already recorded: this transport's ServeMux is the framework's own type, so it writes the matched pattern onto the request value at dispatch and every handler it reaches is keyed by its route without asking. The entry exists because a handler rewritten from the net/http source calls it, and a call that vanished would be a compile error in generated code.

It is not a stub for a missing feature. It is the same feature arriving one layer earlier, which is why nothing here can improve on what the mux recorded.

func SetSocketDefaults

func SetSocketDefaults(opts SocketOptions)

SetSocketDefaults installs the process-wide socket options. It is shared with the net/http runtime, so installing them once covers both.

func SetStreamErrorHandler

func SetStreamErrorHandler(fn func(error))

SetStreamErrorHandler installs what receives a stream failure raised after the response committed. It is process-wide and shared with the net/http half.

func SpanID

func SpanID(ctx context.Context) string

SpanID returns the current span ID, or an empty string outside a trace.

func SpanIDContext

func SpanIDContext(ctx context.Context) string

SpanIDContext is SpanID for code below the handler.

func Start

Start performs framework initialization and returns the request chain together with the shutdown that releases what it opened.

It is the second transport's counterpart to pw.Middlewares, and it is what an application calls when it owns its own listener. Run calls it and owns one.

Every layer it starts is a shared one — pwconfig, pwdatabase, pwsession, pwobservability, pwratelimit — so this reproduces none of that startup and only sequences it. What is genuinely this transport's is the last step, which is the chain.

The shutdown is returned rather than deferred because the caller decides when serving stops. It runs the cleanups in reverse, and is safe to call once.

func TraceID

func TraceID(ctx context.Context) string

TraceID returns the current trace ID, or an empty string outside a trace.

func TraceIDContext

func TraceIDContext(ctx context.Context) string

TraceIDContext is TraceID for code below the handler.

func Traced

func Traced(ctx context.Context) bool

Traced reports whether a valid span context is active.

func TracedContext

func TracedContext(ctx context.Context) bool

TracedContext is Traced for code below the handler.

func Transaction

func Transaction(ctx context.Context, fn func(context.Context) error) error

Transaction runs fn inside a database transaction on the effective group.

func TransactionContext

func TransactionContext(ctx context.Context, fn func(context.Context) error) error

TransactionContext is Transaction for code below the handler.

func WantsLive

func WantsLive(r *fasthttp.RequestCtx) bool

WantsLive reports whether this request asked for deliveries instead of a document, which is what a page renders differently for.

It is the counterpart of the net/http half's predicate, and the reason both exist is this one: the mode arrives in a header, and a page that read the header itself would be a page only one transport could serve.

func WantsUpdate

func WantsUpdate(r *fasthttp.RequestCtx) bool

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, and a page carrying the runtime takes the regions instead. Keeping it to one predicate is what stops the two paths from drifting apart.

func WantsValue

func WantsValue(r *fasthttp.RequestCtx) bool

WantsValue reports a server function called from a script, which is the third branch of an action handler beside WantsUpdate and the ordinary response.

func WebSocket

func WebSocket[In, Out any](r *fasthttp.RequestCtx, fn func(*Socket[In, Out]) error) error

WebSocket upgrades the request, runs fn against a typed socket, and closes the socket when fn returns.

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. fn's own error is post-commit and reaches SetStreamErrorHandler.

fn runs after the handler has returned, from the hijacked connection, so it must not read r: everything it needs is captured before WebSocket returns. This transport closes the connection when fn returns, which is what the callback shape wants.

The origin check is this framework's, resolved through the same declared proxies and trusted origins the net/http half reads, so one deployment answers one way whichever runtime serves it.

func WebSocketWith

func WebSocketWith[In, Out any](r *fasthttp.RequestCtx, opts SocketOptions, fn func(*Socket[In, Out]) error) error

WebSocketWith is WebSocket with per-call options.

func WithLogAttributes

func WithLogAttributes(ctx context.Context, attributes ...Attribute) context.Context

WithLogAttributes adds attributes to every record taken from the returned context.

func WriteAPI

func WriteAPI[T any](r *fasthttp.RequestCtx, value T)

WriteAPI writes one typed API response, or the problem that describes why it could not.

func WriteHTML

func WriteHTML(r *fasthttp.RequestCtx, leaf HTMLFragment)

WriteHTML renders one generated fragment inside the registered document shell, which is the entry an ordinary handler calls.

func WriteHTMLChain

func WriteHTMLChain(r *fasthttp.RequestCtx, wrappers []HTMLWrapper, leaf HTMLFragment, options ...HTMLOption)

WriteHTMLChain renders generated wrappers around one leaf.

Nothing commits until the whole chain has rendered, so a failure part way through still becomes a problem response rather than a truncated document. A chain carrying await boundaries settles them before writing: this half renders buffered where the net/http one can stream, which costs time to first byte and changes no bytes. Streaming is what the deferred htmlupdate port unlocks, since the boundary delivery path holds a flusher.

func WriteHTMLFragment

func WriteHTMLFragment(r *fasthttp.RequestCtx, fragment HTMLFragment)

WriteHTMLFragment renders one fragment with no document around it, for a response that replaces a region of a page the client already has.

func WriteHTMLPage

func WriteHTMLPage(r *fasthttp.RequestCtx, 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 what generated page tree code calls: that code knows the ancestor layouts of a route and must not name the document, which stays the framework's.

func WriteProblem

func WriteProblem(r *fasthttp.RequestCtx, err error)

WriteProblem answers with the problem document describing err, or with the application's error page when the client would rather have one.

One handler answers a browser form post and an API client on the same route, so which representation a failure takes is the client's to say. It is read from Accept by the shared rule both transports use, and the page it reaches is the one registered in the shared registry — so an application registers its error pages once and both builds serve them.

func WriteStatus

func WriteStatus[T any](r *fasthttp.RequestCtx, status int, value T)

WriteStatus is WriteAPI with the status the handler chose.

The name is pw's, not a description of what it does. An earlier draft called it WriteAPIStatus, which reads better and does not work: a rewritten call keeps its selector and only moves its qualifier, so pw.WriteStatus becomes pwfast.WriteStatus and a better name here is simply a missing symbol there.

func WriteStream

func WriteStream[T any](r *fasthttp.RequestCtx, fn func(*Stream[T]) error)

WriteStream answers with a typed event stream, running fn to produce it.

The callback is the shape rather than a returned stream because this transport registers a body writer that runs after the handler returns, so a stream the handler held would have nothing to write into. The callback returning is the close, and an error from it is post-commit and reaches the installed stream error handler.

func WriteUpdate

func WriteUpdate(r *fasthttp.RequestCtx, 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(r *fasthttp.RequestCtx, 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 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

type Attribute = pwruntime.Attribute

The logging names pw publishes, under the same spelling, so a rewritten handler that logs finds them here.

Logger already crossed; the attribute constructors did not, which made the half that crossed unusable: Warn and its siblings take Attribute values and nothing here could build one. A handler calling pw.Logger(ctx).Warn(msg, pw.Err(err)) — the shape every example writes — was rewritten into a reference to a name this package did not declare, and the second build failed to compile with no earlier sign. Found 2026-08-11 by the websocket example.

Every declaration is pwruntime's, aliased rather than redeclared, so a record written on one transport is the same value on the other.

func Bool

func Bool(key string, value bool) Attribute

func Duration

func Duration(key string, value time.Duration) Attribute

func Err

func Err(err error) Attribute

Err records an error as an attribute rather than as formatted message text, so a backend can index it.

func Float64

func Float64(key string, value float64) Attribute

func Int

func Int(key string, value int) Attribute

func Int64

func Int64(key string, value int64) Attribute

func String

func String(key, value string) Attribute

type Authentication

type Authentication = pwruntime.Authentication

Authentication is the verified authentication result recorded by authentication middleware.

func RequestAuthentication

func RequestAuthentication(ctx context.Context) 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 CORSConfig

type CORSConfig = pwruntime.CORSConfig

SecurityHeadersConfig and its parts are the shared leaf's, so a project configures one set of headers and both builds send it.

func DefaultCORS

func DefaultCORS() CORSConfig

DefaultCORS returns the shipped cross-origin defaults.

type CSRFConfig

type CSRFConfig = pwruntime.CSRFConfig

CSRFConfig is the shared configuration, so one setting protects both builds.

type CSRFRejection

type CSRFRejection func(r *fasthttp.RequestCtx, reason error)

CSRFRejection answers a request the check refused.

type CSRFSecret

type CSRFSecret = middlewares.CSRFSecret

CSRFSecret is the per-session secret the check validates against, the same slot type the other half registers.

type CacheKey

type CacheKey = pwruntime.CacheKey

CacheKey is the identity a cached result is stored under.

type CacheStats

type CacheStats = pwruntime.CacheStats

CacheStats is what one store has answered.

type CacheStore

type CacheStore = pwruntime.CacheStore

CacheStore is one configured data cache.

func MemoStore

func MemoStore(ctx context.Context, name string) (*CacheStore, error)

MemoStore resolves a configured data cache by name.

func MemoStoreContext

func MemoStoreContext(ctx context.Context, name string) (*CacheStore, error)

MemoStoreContext is MemoStore for code below the handler.

type CacheTagger

type CacheTagger = pwruntime.CacheTagger

CacheTagger is the optional half of a key type, naming the tags whose invalidation drops the entry.

type Carrier

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

Carrier carries a session over this transport.

It is three methods, and none of them is a decision: reading the cookies that arrived, setting the ones that leave, and handing over the context. Every rule about what a session does — when a token rotates, which cookie a stale record clears, what separates browser state that is merely old from a backend that is down — stays in the session package and is reached through Manager.Resolve. That is the point of the seam: a session is the last thing that should exist twice, because two implementations of when a session ends are two chances to leave one valid that should not be.

func (Carrier) Context

func (c Carrier) Context() context.Context

Context is the request's context, which is the request value itself.

func (Carrier) Cookies

func (c Carrier) Cookies() []*http.Cookie

Cookies returns the cookies the request carried.

They are translated into net/http's cookie struct, which the session package uses as its vocabulary: it is a plain description of a cookie with no transport in it. Only the name and the value are read from a request cookie — a browser sends nothing else — so nothing is lost in the translation.

func (Carrier) SetCookie

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

SetCookie adds one Set-Cookie to the response.

type FieldError

type FieldError = pwruntime.FieldError

The application-facing problem is pwruntime's, the same declaration pw aliases, so a problem built on one side is the value the other inspects and unwraps. An earlier draft aliased the module's two-field problem body under this name, which made one name mean two types.

HTTPError stays the module's, because it is the module's own error and both of its runtimes already alias one declaration of it.

func Field

func Field(field, location, message string) FieldError

The problem constructors are pwruntime's too, so a rewritten call finds the same names building the same value.

type Frame

Frame is one positioned step of the chain.

type GuardPolicy

type GuardPolicy struct {
	// Protected reports whether a path requires an authenticated caller. A nil
	// value protects nothing, which is the shape a deployment with no
	// protection configured has.
	Protected func(path string) bool
	// LoginURL is where an unauthenticated browser is sent. An empty result
	// answers 401 instead, which is also what Redirect being false does.
	LoginURL func(path string) string
	// Redirect sends a browser to LoginURL; without it an unauthenticated
	// request is answered 401 whatever it accepts. An API-only deployment wants
	// the second, and a redirect there would answer a fetch with a login page.
	Redirect bool
	// BearerRealm names the scheme a 401 asks for, per RFC 6750, so a client
	// that sent nothing learns what to send. Empty sends no challenge.
	BearerRealm string
}

GuardPolicy is what a guard needs to decide, in a form that names no transport and no identity provider.

It is supplied rather than derived because deciding is not this package's job: which paths are protected and where an unauthenticated visitor is sent are an authentication plugin's, and this half applies what that plugin resolved. The same separation lets an application without one write a policy of its own.

type HSTSConfig

type HSTSConfig = pwruntime.HSTSConfig

SecurityHeadersConfig and its parts are the shared leaf's, so a project configures one set of headers and both builds send it.

type HTMLFragment

type HTMLFragment = htmlbind.Fragment

The composition types are htmlbind's on both transports. They describe rendering rather than a transport, so there is nothing here to mirror: pw aliases the same declarations, and a fragment built by generated code is the same value whichever half receives it.

type HTMLOption

type HTMLOption = htmlbind.Option

The composition types are htmlbind's on both transports. They describe rendering rather than a transport, so there is nothing here to mirror: pw aliases the same declarations, and a fragment built by generated code is the same value whichever half receives it.

type HTMLWrapper

type HTMLWrapper = htmlbind.Wrapper

The composition types are htmlbind's on both transports. They describe rendering rather than a transport, so there is nothing here to mirror: pw aliases the same declarations, and a fragment built by generated code is the same value whichever half receives it.

type HTTPError

type HTTPError = fasthttpbind.HTTPError

The application-facing problem is pwruntime's, the same declaration pw aliases, so a problem built on one side is the value the other inspects and unwraps. An earlier draft aliased the module's two-field problem body under this name, which made one name mean two types.

HTTPError stays the module's, because it is the module's own error and both of its runtimes already alias one declaration of it.

type Level

type Level = pwruntime.Level

The logging names pw publishes, under the same spelling, so a rewritten handler that logs finds them here.

Logger already crossed; the attribute constructors did not, which made the half that crossed unusable: Warn and its siblings take Attribute values and nothing here could build one. A handler calling pw.Logger(ctx).Warn(msg, pw.Err(err)) — the shape every example writes — was rewritten into a reference to a name this package did not declare, and the second build failed to compile with no earlier sign. Found 2026-08-11 by the websocket example.

Every declaration is pwruntime's, aliased rather than redeclared, so a record written on one transport is the same value on the other.

type Locale

type Locale = pwruntime.Locale

Locale identifies one locale the project declared in its i18n block.

func LocaleContext

func LocaleContext(ctx context.Context) Locale

LocaleContext is RequestLocale for code below the handler.

func RequestLocale

func RequestLocale(ctx context.Context) Locale

RequestLocale returns the locale resolved for this request.

type Log

type Log = pwruntime.Logger

The logging names pw publishes, under the same spelling, so a rewritten handler that logs finds them here.

Logger already crossed; the attribute constructors did not, which made the half that crossed unusable: Warn and its siblings take Attribute values and nothing here could build one. A handler calling pw.Logger(ctx).Warn(msg, pw.Err(err)) — the shape every example writes — was rewritten into a reference to a name this package did not declare, and the second build failed to compile with no earlier sign. Found 2026-08-11 by the websocket example.

Every declaration is pwruntime's, aliased rather than redeclared, so a record written on one transport is the same value on the other.

type Middleware

Middleware is the chain shape on this transport.

It is the same idea as the other half's func(http.Handler) http.Handler and not the same type, which is the point decision:backend-specific-middleware already settled: an application's own middleware is written per backend, because a frame that wraps a handler necessarily names the handler.

What is portable is what a frame does rather than how it wraps. A frame that reads a header, decides something, and records it for the rest of the chain has one implementation of the deciding and two of the reading and recording.

func AccessLog

func AccessLog() Middleware

AccessLog writes one completion record per request.

The status and the size are read off the response rather than out of a tracking writer. That is not a shortcut: this transport buffers an ordinary response, so both are simply there once the handler returns, where the other half has to wrap the writer to observe them at all.

A streamed response is the exception, and reading its size is not merely wrong there but fatal: Response.Body on a body stream drains the stream into memory to answer, so a live subscription — which by design does not end until its watchdog closes it — would be consumed here and never reach the client at all. The record says the size is unknown instead, which is the truth at the moment the handler returned.

func CSRF

func CSRF(config CSRFConfig, cookie session.CookieOptions, sameSite http.SameSite,
	reject CSRFRejection, trustedProxies []*net.IPNet) (Middleware, error)

CSRF refuses a cross-site request that carries no proof it came from a page this deployment served.

Every decision it makes is the shared one. The origin comparison, the path canonicalisation, the safe-method set and the token derivation all live outside this file, and this supplies the request facts each of them reads. That split is the whole reason the check is portable: what is left here is which header to peek at, and a wrong answer there fails loudly, where a wrong answer in any of the shared parts would fail by accepting a request it should have refused.

Two checks rather than one, in this order. The origin comparison is what stops a cross-site form post, and it runs first because it needs no session and refuses the cheapest attack before anything is allocated. The token comparison is what stops a request from a page this deployment served but a different browser state — most importantly a token minted before a sign-in and presented after one.

func DocumentationEndpoints

func DocumentationEndpoints(openAPIPath, docKind, docPath string,
	catalog pwruntime.ResolvedAPICatalog) Middleware

DocumentationEndpoints answers the OpenAPI document and the UI over it.

Unlike the probes it belongs beneath whatever protects the routes it describes: an API description is a map of the whole application surface, so reaching it costs a session where the configuration says so. That is why its slot is below the guard rather than beside the operational frame, and why this returns a frame rather than being folded into the one above it.

A configuration naming neither returns the handler unchanged, so the common case adds nothing to the chain.

func FrameworkAssets

func FrameworkAssets() Middleware

FrameworkAssets answers the framework's own browser assets, and closes the namespace they live in.

Closing it is the second half and not an extra: the prefix is reserved, so an unclaimed path inside it — a stale script revision, a probe — answers 404 here rather than reaching application routing. One reserved prefix is then a single routing and access rule instead of a hole an application could accidentally serve through.

func Guard

func Guard(policy GuardPolicy) Middleware

Guard requires an authenticated caller on every protected path.

The path is canonicalised through the shared check first and a request whose path cannot be matched unambiguously is refused, because such a path could select a different routed target than the one this decided about. That is the same refusal the CSRF check makes, for the same reason, from the same function.

func InjectResources

func InjectResources(resources pwruntime.Resources) Middleware

InjectResources publishes the process runtime resources — the loaded configuration, the logger, the database pool — on every request.

The other half derives a context carrying them and hands it to the next handler; this one writes them into the request value. Everything downstream reads them the same way, because the request value answers Value from the store this writes to. The capsule is prepared once here rather than once per request, exactly as the other transport's frame prepares it: a capsule with no per-request state is shared rather than re-copied to the heap each time.

func MaxRequestBody

func MaxRequestBody(limit int64) Middleware

MaxRequestBody refuses a request whose body is larger than limit.

A non-positive limit disables the check, which is the same reading the other half gives it.

The check is on the declared length rather than on a wrapped reader, because this transport has already read the body by the time a handler runs: the server's own MaxRequestBodySize is what stops an oversized one from being read at all, and this frame is the per-chain expression of the same limit.

func Metrics

func Metrics(metrics *pwruntime.Metrics) Middleware

Metrics records the http.server instruments of one request.

It is a frame of its own rather than a line inside the tracing frame, for the reason its net/http counterpart is: the two are installed independently, and a deployment sampling one trace in a thousand still counts every request.

func OperationalEndpoints

func OperationalEndpoints(health, readiness string, resources pwruntime.Resources) Middleware

OperationalEndpoints answers the liveness and readiness probes above everything that authenticates.

The probes reveal only status and are reachable by anything that can reach the port, which is what a liveness probe needs and what keeps a dependency outage from turning into a restart loop. Readiness is the shared probe, so the same process reports the same readiness whichever transport asked.

A path left empty installs nothing for it, which is how a deployment turns one off.

func Otel

func Otel(options ...OtelOption) Middleware

Otel extracts W3C Trace Context, creates a server span, and installs it on the request. With no options it uses trace.DefaultProvider.

The span is opened outside every positioned frame, so a request root span covers the whole chain and every record taken inside it correlates. That is why its slot is the smallest one.

func ProcessRateLimiter

func ProcessRateLimiter(config RateLimitConfig, deps RateLimitDeps) (Middleware, error)

ProcessRateLimiter is the unkeyed total arrival ceiling.

It is a separate frame from RateLimiter because it needs nothing resolved and belongs further out, where a refused request has cost less. It is also the only layer that sees a flood spread across many addresses, each of them staying under the per-address count by construction.

func PublicAssets

func PublicAssets(config PublicAssetConfig, embedded fs.FS) (Middleware, error)

PublicAssets answers static files from the embedded tree, above everything that authenticates.

Every decision is the shared one: which names may be served, which representation an Accept-Encoding value selects, what a manifest entry says. Only reading the headers and writing the bytes is here, which is what a second copy of this may safely be — the path check in particular is not, and is not copied: two implementations of which names may be served are two chances to serve one that must not be.

func RateLimiter

func RateLimiter(config RateLimitConfig, deps RateLimitDeps) (Middleware, error)

RateLimiter bounds arrivals per caller.

It is named for the frame rather than for the limit, because RateLimit here is already the response metadata a refusal carries — the same spelling the other transport gives it.

The identity is the authenticated subject where there is one and the resolved client address otherwise, so it must be installed below whatever establishes authentication — which the shared slot ordering does. The process ceiling needs nothing resolved and is installed separately, further out.

func Recover

func Recover(handler PanicHandler) Middleware

Recover converts a panic into a response written by handler. A nil handler logs the panic and writes a plain 500.

It recovers more completely than the other half can, and the difference is the transport rather than the code: this one buffers a response until the handler returns, so whatever a failed handler had written is still discardable and the 500 is the only thing the client sees. On net/http a response that has already committed can only be stopped, not taken back.

What it does not reach is a panic inside a body stream writer, because that callback runs after the handler has returned and this frame with it.

func RequestID

func RequestID(options ...RequestIDOption) Middleware

RequestID validates or creates a request ID, echoes it on the response, and records it as a log attribute every later record carries.

The check on a client-supplied value is the shared one, because it is a security check rather than a convenience: the value arrives from the client and leaves in a response header, so a second copy of the rule would be a second chance to get it wrong.

Where this differs from the other half is only the recording. That one derives a context per frame and hands it on; here the request value is the context, so the attribute is written into it in place. Everything that reads it afterwards is unchanged, because the request value answers Value from the same store.

func RequestTimeout

func RequestTimeout(timeout time.Duration) Middleware

RequestTimeout bounds how long a request may take. A timeout of zero or less returns a pass-through middleware.

This is the one frame whose meaning genuinely differs between the transports, and the difference is worth stating rather than smoothing over.

The other half installs a deadline on the request context. Everything the handler does with that context — a query, an outbound call, an await boundary — observes it and stops, and the handler itself returns.

Here the request value is the context, and a frame cannot give it a deadline it did not have. So the bound is the transport's own: the response is answered with 408 when the handler has not returned in time, and the handler goroutine keeps running until it finishes on its own. The request is bounded from the client's side, not from the handler's.

A handler that needs its own work cancelled derives a context from the request and passes that down, which is portable and reads the same on both.

func ResolveClientAddress

func ResolveClientAddress(trustedProxies []*net.IPNet) Middleware

ResolveClientAddress records the caller every downstream bound counts against.

The walk through the forwarded chain is the shared one, so this transport and the other name the same caller for the same request. Getting that wrong is quiet: an unresolved address counts the proxy, and every rate limit and live bound then applies to one address for every visitor.

func SecurityHeaders

func SecurityHeaders(config SecurityHeadersConfig, option ...SecurityHeadersOption) (Middleware, error)

SecurityHeaders sets the policy headers on every response.

The configuration is validated and reduced to a header set by the shared leaf, at construction, so a misconfiguration is an error before the port is bound and the two transports send the same headers rather than two computations that agree.

func Session

func Session(manager *session.Manager, unavailable UnavailableHandler) Middleware

Session resolves the session of every request and publishes it for the rest of the chain.

The resolution is the session package's, so this transport and the other apply one set of rules to one browser. What differs is only where the resolved session is recorded: the other half derives a context and hands it on, and this one writes into the request value.

A nil manager installs nothing, which is how a deployment with session storage disabled opts out — and it opts out by having no frame rather than by having an inert one, because a session frame that silently does nothing is a control that looks installed.

type Option

type Option func(*startOptions) error

Option configures startup.

func WithPublicFS

func WithPublicFS(publicFS fs.FS) Option

WithPublicFS supplies the embedded public tree, rooted at its public directory. An embed is a fact of the binary rather than of a settings file, which is why it is passed rather than configured.

func WithRuntimeOptions

func WithRuntimeOptions(apply func(RuntimeOptions) RuntimeOptions) Option

WithRuntimeOptions folds one contribution into what the chain is built from.

It is how a plugin that installs frames reaches this transport. There is no extension registry here — an imported capability cannot install a frame this chain would gain without the application saying so — which is why a plugin serving both transports registers on the other one and is named here. An application's own middleware has RegisterMiddleware instead. An authentication plugin's Apply is exactly this shape:

auth, err := authfast.Setup(ctx)
pwfast.Run(ctx, handler, pwfast.WithRuntimeOptions(auth.Apply))

func WithSetup

func WithSetup(setup func(context.Context) (func(RuntimeOptions) RuntimeOptions, error)) Option

WithSetup folds in a contribution that has to be built from the resolved configuration first.

It is the shape a plugin with startup of its own needs. WithRuntimeOptions takes a contribution the caller already has; this takes the thing that makes one, and is handed a context carrying the settings, the logger and the pool — the same capsule a request is served with. An authentication plugin's Contribute is exactly this shape:

pwfast.Run(ctx, handler, pwfast.WithSetup(authfast.Contribute))

It runs after the shared layers and before the chain is composed, so a plugin reads a pool that is open and a session manager that exists.

type OtelOption

type OtelOption func(*otelConfig)

OtelOption configures Otel.

func WithSpanName

func WithSpanName(format func(*fasthttp.RequestCtx) string) OtelOption

WithSpanName replaces how a request span is named.

func WithTracerProvider

func WithTracerProvider(provider *trace.Provider) OtelOption

WithTracerProvider replaces the provider spans are created from.

type PanicHandler

type PanicHandler func(r *fasthttp.RequestCtx, err error)

PanicHandler writes the response for a panic recovered by Recover.

type Pending

type Pending[T any] = htmlbind.Pending[T]

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.

func Failed

func Failed[T any](err error) Pending[T]

Failed returns a handle that has already settled to err. The boundary that awaits it renders its recover subtree.

func Go

func Go[T any](ctx context.Context, work func(context.Context) (T, error)) Pending[T]

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.

The context a handler passes here is normally the request value itself, which is this transport's context. That value is pooled and invalid once the handler returns — but a render settles every boundary before returning, so the work is done with it by then. Work that must outlive the response takes a context derived from context.Background(), which is the same rule the other transport's pooling-free request would not have taught.

func Resolved

func Resolved[T any](value T) Pending[T]

Resolved returns a handle that has already settled to value. It is what a handler passes when it computed the value itself, and what a test passes instead of starting a goroutine.

type Problem

type Problem = pwruntime.Problem

The application-facing problem is pwruntime's, the same declaration pw aliases, so a problem built on one side is the value the other inspects and unwraps. An earlier draft aliased the module's two-field problem body under this name, which made one name mean two types.

HTTPError stays the module's, because it is the module's own error and both of its runtimes already alias one declaration of it.

func BadRequest

func BadRequest(values ...any) Problem

func Conflict

func Conflict(values ...any) Problem

func Forbidden

func Forbidden(values ...any) Problem

func InternalServerError

func InternalServerError(values ...any) Problem

func NotFound

func NotFound(values ...any) Problem

func PayloadTooLarge

func PayloadTooLarge(values ...any) Problem

func RateLimited

func RateLimited(rate RateLimit, values ...any) Problem

func ServiceUnavailable

func ServiceUnavailable(values ...any) Problem

func TooManyRequests

func TooManyRequests(values ...any) Problem

func Unauthorized

func Unauthorized(values ...any) Problem

func Validation

func Validation(fields ...FieldError) Problem

Validation reports a 400 response carrying every detected field failure.

type PublicAssetConfig

type PublicAssetConfig = middlewares.PublicAssetConfig

PublicAssetConfig is the shared configuration, so one setting serves both builds from one tree.

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 QueryValues added in v0.5.4

type QueryValues = fasthttpbind.QueryValues

QueryValues is the request's query string split once into raw key=value spans, in wire order — the same alias the net/http half holds, so a decoder moved between transports keeps its type.

func Queries

func Queries(r *fasthttp.RequestCtx) QueryValues

Queries returns the parsed query, for a decoder reading several parameters from one request.

Since system:tinybind v0.5.27 it goes through the module rather than QueryArgs: the driver's parser admits pairs url.ParseQuery drops, and the two runtimes then bound different values for a query the client chose. One parser is what makes the answer one.

type RateLimit

type RateLimit = pwruntime.RateLimit

The application-facing problem is pwruntime's, the same declaration pw aliases, so a problem built on one side is the value the other inspects and unwraps. An earlier draft aliased the module's two-field problem body under this name, which made one name mean two types.

HTTPError stays the module's, because it is the module's own error and both of its runtimes already alias one declaration of it.

type RateLimitConfig

type RateLimitConfig = pwratelimit.Config

RateLimitConfig bounds how often one caller, and the process as a whole, may arrive within a window.

type RateLimitCounter

type RateLimitCounter = pwratelimit.Counter

RateLimitCounter is the storage a limiter counts in.

type RateLimitDegraded

type RateLimitDegraded func(r *fasthttp.RequestCtx, err error)

RateLimitDegraded is called when the counter store could not answer.

The request is admitted regardless, per pwratelimit.Limiter.Admit. This exists so that silently-not-limiting is observable, which is the worst of the three states to be in unknowingly.

type RateLimitDeps

type RateLimitDeps struct {
	// Counter is the storage. It is required once the limiter is enabled.
	Counter RateLimitCounter
	// Exempt are the paths this limiter never counts. The framework fills it
	// with the endpoints it owns and routes itself — the operational probes and
	// the public asset mount — and it is not a deployment setting.
	Exempt []string
	// Reject writes the refusal. A nil value writes the framework problem
	// document, which is what a caller on either transport receives.
	Reject RateLimitRejection
	// Degraded observes an admission made without a working store.
	Degraded RateLimitDegraded
}

RateLimitDeps are the runtime pieces the limiter needs beyond its configuration.

type RateLimitRejection

type RateLimitRejection func(r *fasthttp.RequestCtx, limit pwruntime.RateLimit)

RateLimitRejection writes the response for a refused request.

type RequestIDOption

type RequestIDOption func(*requestIDConfig)

RequestIDOption configures RequestID.

func WithRequestIDGenerator

func WithRequestIDGenerator(generate func() string) RequestIDOption

WithRequestIDGenerator replaces the generator used when the client did not send a usable request ID.

func WithRequestIDHeader

func WithRequestIDHeader(name string) RequestIDOption

WithRequestIDHeader replaces the default X-Request-ID header name.

type RouteInstaller

type RouteInstaller interface {
	Handle(method, path string, handler fasthttp.RequestHandler)
}

RouteInstaller is what generated route registration installs on.

It exists because the two transports register a route differently and the generated file has to name one shape. The other half's routes are registered by authored wiring the build tag excludes — a mux built in an init, a HandleFunc per handler — and this build has to get them from somewhere. What it gets is one function per package, emitted from the same route table the other half declares, so the two serve the same addresses.

The method and the path arrive apart because that is how the generated call spells them. Everything else about the pattern is Go 1.22's, unchanged, and is translated here rather than by the generator: a catch-all, a subtree and the {$} marker then mean on this transport exactly what they mean on the other, decided in one place.

func Routes

func Routes(mux *ServeMux) RouteInstaller

Routes adapts a mux to what generated route registration installs on:

mux := pwfast.NewServeMux()
handlers.RegisterRoutes(pwfast.Routes(mux))

type RuntimeOptions

type RuntimeOptions struct {
	// Resources is the capsule every request is served with. A zero value
	// serves requests with the process defaults.
	Resources pwruntime.Resources
	// TrustedProxies are the networks whose forwarding headers this deployment
	// reads.
	TrustedProxies []*net.IPNet
	// Tracing installs the request root span. It is a runtime option rather
	// than a setting because whether a span has anywhere to go is decided by
	// the exporter this process built, not by a configuration key.
	Tracing bool
	// PublicFS is the embedded public tree. It is supplied rather than read
	// from configuration because an embed is a compile-time fact of the
	// application binary rather than something a settings file can name.
	PublicFS fs.FS
	// Session is the manager the session frame resolves through, or nil where a
	// deployment disabled session storage. It is supplied rather than built
	// here because building one is startup work — a registry, a keyring, a
	// backend — and startup belongs to whichever runtime binds configuration.
	Session *session.Manager
	// SessionCookie and SessionSameSite describe the cookie the CSRF companion
	// is issued beside, so the two travel with the same policy.
	SessionCookie   session.CookieOptions
	SessionSameSite http.SameSite
	// Guard is the authorization policy. It is supplied rather than derived
	// because deciding which paths are protected belongs to an authentication
	// plugin, and this half applies what that plugin resolved.
	Guard GuardPolicy
	// RateLimitCounter is the storage the limiter counts in, or nil where a
	// deployment left the limiter off. Like the session manager it is supplied
	// rather than opened here, because opening it is startup work: a Redis
	// counter dials a server and refuses to start against one it cannot reach.
	//
	// A configuration that enables the limiter and supplies no counter is
	// refused rather than served without one, per policy:absent-rather-than-stubbed:
	// a limiter that admits everything is a control that looks installed.
	RateLimitCounter RateLimitCounter
	// Extra frames are installed alongside the framework's, positioned by their
	// own slots.
	Extra []Frame
}

RuntimeOptions are what Middlewares needs that configuration does not carry.

type SecurityHeadersConfig

type SecurityHeadersConfig = pwruntime.SecurityHeadersConfig

SecurityHeadersConfig and its parts are the shared leaf's, so a project configures one set of headers and both builds send it.

func DefaultSecurityHeaders

func DefaultSecurityHeaders() SecurityHeadersConfig

DefaultSecurityHeaders returns the classic mode defaults.

type SecurityHeadersOption

type SecurityHeadersOption func(*securityHeadersOptions)

SecurityHeadersOption configures SecurityHeaders.

func WithCORS

func WithCORS(config CORSConfig, csrfHeader string) SecurityHeadersOption

WithCORS gives the frame the cross-origin policy to answer as well. It is one frame on this transport for the reason it is one on the other: both halves are browser policy written before commitment, and the marking has to precede every refusal written below.

func WithTrustedProxies

func WithTrustedProxies(networks []*net.IPNet) SecurityHeadersOption

WithTrustedProxies accepts X-Forwarded-Proto from the listed networks when deciding whether a request arrived over HTTPS. Without it only a direct TLS connection counts as HTTPS.

type ServeMux

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

ServeMux routes Go 1.22 patterns on this transport.

It is the same name and the same patterns as the other half, over a trie router instead of net/http's matcher. An application writes one route table and both builds register it, which is the point: a route table is the part of an application least willing to be written twice.

What it does is translate at registration. The pattern syntax is close enough that most of the translation is nothing — a named parameter is spelled the same in both — and the rest is three rewrites and two refusals, each of which is documented on the function that performs it.

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux returns a mux whose behaviour matches Go 1.22's.

The four flags are set rather than left at the router's defaults, because the defaults are that router's opinion and the contract here is the other transport's behaviour.

func (*ServeMux) Handle

func (m *ServeMux) Handle(pattern string, handler fasthttp.RequestHandler)

Handle registers a handler for one Go 1.22 pattern.

func (*ServeMux) HandleFunc

func (m *ServeMux) HandleFunc(pattern string, handler func(*fasthttp.RequestCtx))

HandleFunc is Handle for a bare function, and is the method generated route registration calls.

func (*ServeMux) Handler

func (m *ServeMux) Handler(ctx *fasthttp.RequestCtx)

Handler serves one request, and is the value passed to a server.

It is a method rather than the mux itself being the handler because fasthttp's handler is a function type rather than an interface, so there is nothing for a struct to implement.

type Slot

type Slot = pwruntime.Slot

Slot orders every frame of the request chain, and the numbers are the shared leaf's, so a chain assembled here runs in the order the other transport's does.

That the numbers are shared is the point rather than a tidiness: a chain whose frames run in a different order on the second transport is a different application. A guard running after the session on one and before it on the other would authorize differently, and nothing about either response would say so.

type Socket

type Socket[In, Out any] = fasthttpbind.Socket[In, Out]

Socket is the module's own typed WebSocket connection, the same declaration pw aliases, so the value a callback receives is one type across the pair.

type SocketOptions

type SocketOptions = fasthttpbind.SocketOptions

SocketOptions configures one socket. A zero field takes the process default, and nothing reaches the connection as zero.

func SocketDefaults

func SocketDefaults() SocketOptions

SocketDefaults returns the effective process defaults.

type Span

type Span = trace.Span

Span is one unit of traced work.

func StartSpan

func StartSpan(ctx context.Context, name string, attributes ...Attribute) (context.Context, *Span)

StartSpan opens a child of the active span and returns a context carrying it.

func StartSpanContext

func StartSpanContext(ctx context.Context, name string, attributes ...Attribute) (context.Context, *Span)

StartSpanContext is StartSpan for code below the handler.

func StartSpanKind

func StartSpanKind(ctx context.Context, name string, kind SpanKind, attributes ...Attribute) (context.Context, *Span)

StartSpanKind is StartSpan for work that is not internal.

func StartSpanKindContext

func StartSpanKindContext(ctx context.Context, name string, kind SpanKind, attributes ...Attribute) (context.Context, *Span)

StartSpanKindContext is StartSpanKind for code below the handler.

type SpanKind

type SpanKind = trace.SpanKind

SpanKind describes what relationship a span has to its parent.

type Stream

type Stream[T any] = fasthttpbind.Stream[T]

Stream is the module's own typed event stream, the same declaration pw aliases, so the value a callback receives is one type across the pair.

type UnavailableHandler

type UnavailableHandler func(r *fasthttp.RequestCtx, err error)

UnavailableHandler answers a request whose session could not be read because the backend failed.

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 = pwruntime.UpdateRegion

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.

Jump to

Keyboard shortcuts

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