app

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2026 License: MPL-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultAPIBodyLimit int64 = 1 << 20

DefaultAPIBodyLimit is the generated API request body limit. API handlers receive the raw *http.Request and decode the body themselves, so the limit is enforced by capping request.Body before the handler runs.

View Source
const DefaultActionBodyLimit int64 = 1 << 20

DefaultActionBodyLimit is the generated action request body limit.

View Source
const DefaultRequestTimeout = 25 * time.Second

DefaultRequestTimeout is the per-request handler deadline applied to generated apps. It sits below the server WriteTimeout (30s) so handler context cancellation fires before the connection write deadline.

Variables

View Source
var BoundaryLogger func(message string) = func(message string) {
	log.Print(message)
}

BoundaryLogger receives recovered panics from request-time handlers. The message and stack are secret-redacted before they reach it. Set it to nil to silence recovered-panic logging. It defaults to the standard log package.

Functions

func ApplyMiddlewares added in v0.5.0

func ApplyMiddlewares(next http.Handler, middlewares ...Middleware) http.Handler

ApplyMiddlewares wraps next with middlewares in declaration order. The first middleware in the slice runs first for each request.

func CSRF added in v0.1.5

func CSRF(ctx context.Context) string

CSRF returns the generated CSRF token attached to a request context.

func CSRFInjectHTML added in v0.5.0

func CSRFInjectHTML(response http.ResponseWriter, request *http.Request, payload []byte, source CSRFTokenSource) ([]byte, bool)

CSRFInjectHTML injects a hidden CSRF token into HTML POST forms. It returns false after writing a no-store 500 response when token generation fails.

func LoadAssetManifest

func LoadAssetManifest(root fs.FS) asset.Manifest

LoadAssetManifest reads gowdk-assets.json from generated app output.

func LocalTraceAccess added in v0.5.0

func LocalTraceAccess(request *http.Request) bool

LocalTraceAccess allows the trace viewer only from loopback clients. Generated apps use this as the default gate when the observability viewer is enabled.

func Params added in v0.1.5

func Params(ctx context.Context) map[string]string

Params returns a copy of route params attached by generated runtime adapters.

func RecoverEndpointPanic added in v0.1.5

func RecoverEndpointPanic(writer http.ResponseWriter, request *http.Request, value any)

RecoverEndpointPanic writes a no-store endpoint error page for a recovered generated action or API panic when the response has not started yet.

func RecoverSSRRoutePanic added in v0.1.5

func RecoverSSRRoutePanic(writer http.ResponseWriter, request *http.Request, value any)

RecoverSSRRoutePanic writes a no-store SSR route error page for a recovered generated route panic when the response has not started yet.

func Request added in v0.1.5

func Request(ctx context.Context) (*http.Request, bool)

Request returns the HTTP request attached by generated runtime adapters.

func SPACandidates added in v0.1.5

func SPACandidates(requestPath string) []string

func Session added in v0.1.5

func Session(ctx context.Context) any

Session returns application session state attached to a request context.

func Trace added in v0.5.0

func Trace(ctx context.Context, message string, attrs map[string]any)

Trace records a redacted user event on the active span. It is intentionally small so Go handlers can call app.Trace(ctx, "loaded patient", attrs) without depending on a hosted tracing backend.

func TypedParams added in v0.1.5

func TypedParams(ctx context.Context) map[string]any

TypedParams returns decoded route params attached by generated runtime adapters. Untyped route params are still available as strings.

func WithCSRF added in v0.1.5

func WithCSRF(ctx context.Context, token string) context.Context

WithCSRF stores a generated CSRF token in a context.

func WithEndpoint added in v0.1.5

func WithEndpoint(ctx context.Context, endpoint EndpointMetadata) context.Context

WithEndpoint stores generated endpoint metadata in a context.

func WithParams added in v0.1.5

func WithParams(ctx context.Context, params map[string]string) context.Context

WithParams stores route params in a context.

func WithRequest added in v0.1.5

func WithRequest(ctx context.Context, request *http.Request) context.Context

WithRequest stores the current HTTP request in a context for generated backend handlers.

func WithRoute added in v0.1.5

func WithRoute(ctx context.Context, route RouteMetadata) context.Context

WithRoute stores generated route metadata in a context.

func WithSession added in v0.1.5

func WithSession(ctx context.Context, session any) context.Context

WithSession stores application session state in a context.

func WithTypedParams added in v0.1.5

func WithTypedParams(ctx context.Context, params map[string]any) context.Context

WithTypedParams stores decoded route params in a context.

func WriteErrorPage added in v0.1.5

func WriteErrorPage(writer http.ResponseWriter, request *http.Request, status int, message string)

WriteErrorPage writes a no-store generated HTML error page when available, otherwise it falls back to http.Error.

Types

type BackendHandler added in v0.1.5

type BackendHandler func(http.ResponseWriter, *http.Request) bool

BackendHandler handles one generated backend route and reports whether it wrote a response.

func APIHandler added in v0.1.5

func APIHandler(handler func(context.Context, *http.Request) (response.Response, error)) BackendHandler

APIHandler adapts an API handler.

func APIHandlerWithBodyLimit added in v0.5.0

func APIHandlerWithBodyLimit(bodyLimit int64, handler func(context.Context, *http.Request) (response.Response, error)) BackendHandler

APIHandlerWithBodyLimit adapts an API handler with a custom request body limit. Non-positive limits use DefaultAPIBodyLimit.

func Action0 added in v0.1.5

func Action0(handler func(context.Context) (response.Response, error)) BackendHandler

Action0 adapts a no-input action handler.

func Action0WithBodyLimit added in v0.5.0

func Action0WithBodyLimit(bodyLimit int64, handler func(context.Context) (response.Response, error)) BackendHandler

Action0WithBodyLimit adapts a no-input action handler with a custom request body limit. Non-positive limits use DefaultActionBodyLimit.

func ActionForm added in v0.1.5

func ActionForm[T any](decode func(form.Values) (T, error), handler func(context.Context, T) (response.Response, error)) BackendHandler

ActionForm adapts a typed value action handler with an explicit decoder.

func ActionFormPtr added in v0.1.5

func ActionFormPtr[T any](decode func(form.Values) (T, error), handler func(context.Context, *T) (response.Response, error)) BackendHandler

ActionFormPtr adapts a typed pointer action handler with an explicit decoder.

func ActionFormPtrWithBodyLimit added in v0.5.0

func ActionFormPtrWithBodyLimit[T any](bodyLimit int64, decode func(form.Values) (T, error), handler func(context.Context, *T) (response.Response, error)) BackendHandler

ActionFormPtrWithBodyLimit adapts a typed pointer action handler with an explicit decoder and custom request body limit. Non-positive limits use DefaultActionBodyLimit.

func ActionFormWithBodyLimit added in v0.5.0

func ActionFormWithBodyLimit[T any](bodyLimit int64, decode func(form.Values) (T, error), handler func(context.Context, T) (response.Response, error)) BackendHandler

ActionFormWithBodyLimit adapts a typed value action handler with an explicit decoder and custom request body limit. Non-positive limits use DefaultActionBodyLimit.

func ActionValues added in v0.1.5

func ActionValues(handler func(context.Context, form.Values) (response.Response, error)) BackendHandler

ActionValues adapts a low-level form.Values action handler.

func ActionValuesWithBodyLimit added in v0.5.0

func ActionValuesWithBodyLimit(bodyLimit int64, handler func(context.Context, form.Values) (response.Response, error)) BackendHandler

ActionValuesWithBodyLimit adapts a low-level form.Values action handler with a custom request body limit. Non-positive limits use DefaultActionBodyLimit.

func BackendBoundary added in v0.1.5

func BackendBoundary(kind string, handler BackendHandler) BackendHandler

BackendBoundary wraps a generated backend route handler.

func NotImplemented added in v0.1.5

func NotImplemented(message string) BackendHandler

NotImplemented returns a generated 501 backend handler.

type BackendRoute added in v0.1.5

type BackendRoute struct {
	Method  string
	Path    string
	Kind    string
	Source  gowdktrace.SourceRef
	Handler BackendHandler
}

BackendRoute describes one generated action or API route.

type BackendRouter added in v0.1.5

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

BackendRouter dispatches generated backend routes.

func NewBackendRouter added in v0.1.5

func NewBackendRouter(routes ...BackendRoute) (*BackendRouter, error)

NewBackendRouter creates a backend router and registers the supplied routes.

func (*BackendRouter) API added in v0.1.5

func (router *BackendRouter) API(method string, routePath string, handler BackendHandler) error

API registers a generated API route.

func (*BackendRouter) Action added in v0.1.5

func (router *BackendRouter) Action(routePath string, handler BackendHandler) error

Action registers a generated POST action route.

func (*BackendRouter) Dispatch added in v0.1.5

func (router *BackendRouter) Dispatch(writer http.ResponseWriter, request *http.Request) bool

Dispatch writes a route response when the request matches a backend route.

func (*BackendRouter) Handle added in v0.1.5

func (router *BackendRouter) Handle(method string, routePath string, handler BackendHandler) error

Handle registers a backend route with a normalized method and path.

func (*BackendRouter) HandlerFunc added in v0.1.5

func (router *BackendRouter) HandlerFunc() HandlerFunc

HandlerFunc returns the router as a generated runtime hook.

func (*BackendRouter) ServeHTTP added in v0.1.5

func (router *BackendRouter) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP serves the backend router directly.

type CSRFTokenSource added in v0.1.5

type CSRFTokenSource interface {
	Token(http.ResponseWriter, *http.Request) (string, error)
	FieldName() string
}

CSRFTokenSource generates tokens for generated action forms.

type EndpointMetadata added in v0.1.5

type EndpointMetadata struct {
	Kind      string
	PageID    string
	Name      string
	Method    string
	Path      string
	ErrorPage string
}

EndpointMetadata describes one generated backend endpoint declaration.

func Endpoint added in v0.1.5

func Endpoint(ctx context.Context) (EndpointMetadata, bool)

Endpoint returns generated endpoint metadata attached by generated runtime adapters.

type ErrorPage added in v0.1.5

type ErrorPage struct {
	Path string
}

ErrorPage describes one additional generated HTML error document to load.

type ErrorPages added in v0.1.5

type ErrorPages struct {
	NotFound            []byte
	InternalServerError []byte
	Custom              map[string][]byte
}

ErrorPages stores optional generated HTML error documents.

func LoadErrorPages added in v0.1.5

func LoadErrorPages(root fs.FS) ErrorPages

LoadErrorPages reads optional 404.html and 500.html files from generated output.

func LoadErrorPagesWith added in v0.1.5

func LoadErrorPagesWith(root fs.FS, custom ...ErrorPage) ErrorPages

LoadErrorPagesWith reads default error pages plus extra generated error documents selected by generated route metadata.

type Handler

type Handler struct {
	Root            fs.FS
	Identity        Identity
	SecurityHeaders map[string]string
	Middlewares     []Middleware
	Assets          asset.Manifest
	Backend         HandlerFunc
	Action          HandlerFunc
	API             HandlerFunc
	CSRF            CSRFTokenSource
	ErrorPages      ErrorPages
	Metrics         *Metrics
	Tracer          *gowdktrace.Tracer
	TraceHandler    http.Handler
	TraceAccess     TraceAccess
	SSRExact        HandlerFunc
	SSRDynamic      HandlerFunc

	// Denied holds concrete page routes that declared no guard. Such a page is
	// not public by default: its GET/HEAD route returns 403 until the author
	// opts in with guard public (or a protective guard for request-time pages).
	// Keyed by exact route path.
	Denied map[string]bool

	// DeniedPatterns holds route patterns (e.g. /blog/{slug}) for guardless
	// build-time pages whose paths {} block expands to many concrete artifacts.
	// The exact Denied map cannot enumerate those concrete paths, so the request
	// path is matched against each pattern to deny every expanded instance.
	DeniedPatterns []string

	// RequestTimeout bounds how long a single request's handler context lives.
	// When > 0, the request context is cancelled after the deadline so slow
	// user Go (actions, contracts, SSR) sees ctx.Done() instead of running
	// unbounded and pinning a goroutine. Zero disables the deadline.
	RequestTimeout time.Duration
	// contains filtered or unexported fields
}

Handler serves embedded generated output plus optional action and SSR hooks.

func (Handler) SPAFile added in v0.1.5

func (handler Handler) SPAFile(requestPath string) ([]byte, fs.FileInfo, string, bool)

func (*Handler) ServeHTTP

func (handler *Handler) ServeHTTP(response http.ResponseWriter, request *http.Request)

type HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request) bool

HandlerFunc handles a generated request-time route and reports whether it wrote a response.

func Boundary added in v0.1.5

func Boundary(kind string, handler HandlerFunc) HandlerFunc

Boundary wraps a generated request-time handler with a conservative panic boundary.

type Identity

type Identity struct {
	AppID      string
	ModuleName string
	InstanceID string
}

Identity describes one running generated app instance.

func InstanceIdentity

func InstanceIdentity() Identity

InstanceIdentity reads GOWDK identity settings from the environment.

type Metrics added in v0.1.5

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

Metrics records dependency-free runtime counters for a generated app handler.

func (*Metrics) Snapshot added in v0.1.5

func (metrics *Metrics) Snapshot() MetricsSnapshot

Snapshot returns a point-in-time copy of all counters.

type MetricsSnapshot added in v0.1.5

type MetricsSnapshot struct {
	Requests        uint64 `json:"requests"`
	Health          uint64 `json:"health"`
	CookieAck       uint64 `json:"cookieAck"`
	Backend         uint64 `json:"backend"`
	API             uint64 `json:"api"`
	Action          uint64 `json:"action"`
	SSRExact        uint64 `json:"ssrExact"`
	SSRDynamic      uint64 `json:"ssrDynamic"`
	Static          uint64 `json:"static"`
	MethodNotAllow  uint64 `json:"methodNotAllow"`
	NotFound        uint64 `json:"notFound"`
	Forbidden       uint64 `json:"forbidden"`
	CSRFUnavailable uint64 `json:"csrfUnavailable"`
}

MetricsSnapshot is a stable point-in-time copy of runtime counters.

type Middleware added in v0.5.0

type Middleware func(http.Handler) http.Handler

Middleware wraps the generated app handler chain.

type RouteMetadata added in v0.1.5

type RouteMetadata struct {
	Kind          string
	PageID        string
	Method        string
	Path          string
	Render        string
	Cache         string
	ErrorPage     string
	DynamicParams []string
	RouteParams   []RouteParamMetadata
	Guards        []string
	HasLoad       bool
}

RouteMetadata describes one generated request-time page route.

func Route added in v0.1.5

func Route(ctx context.Context) (RouteMetadata, bool)

Route returns generated route metadata attached by generated runtime adapters.

type RouteParamMetadata added in v0.1.5

type RouteParamMetadata struct {
	Name string
	Type string
}

RouteParamMetadata describes a generated dynamic route parameter.

type TraceAccess added in v0.5.0

type TraceAccess func(*http.Request) bool

TraceAccess decides whether a request may use the generated trace viewer.

Jump to

Keyboard shortcuts

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