relic library

Relic web server framework.

This package re-exports relic_core and relic_io for convenience.

Classes

AcceptEncodingHeader
A class representing the HTTP Accept-Encoding header.
AcceptHeader
A class representing the HTTP Accept header.
AcceptLanguageHeader
A class representing the HTTP Accept-Language header.
AcceptRangesHeader
A class representing the HTTP Accept-Ranges header.
AccessControlAllowHeadersHeader
A class representing the HTTP Access-Control-Allow-Headers header.
AccessControlAllowMethodsHeader
A class representing the HTTP Access-Control-Allow-Methods header.
AccessControlAllowOriginHeader
The HTTP Access-Control-Allow-Origin response header.
AccessControlExposeHeadersHeader
A class representing the HTTP Access-Control-Expose-Headers header.
AccessorState<K, R>
Holds the externalized state for ReadOnlyAccessor instances in a map.
Adapter
An interface for adapters that bridge Relic to specific server implementations.
AdapterCapabilities
What an Adapter can do beyond a plain request and response.
AdapterExchange
One request and its response.
AuthenticationHeader
A class representing the HTTP Authentication header.
AuthenticationParameter
A class representing a key-value pair parameter for authentication.
AuthorizationHeader
An abstract base class representing an HTTP Authorization header.
BasicAuthorizationHeader
Represents Basic authentication using a username and password.
BearerAuthorizationHeader
Represents a Bearer token for HTTP Authorization.
Body
The body of a request or response.
BodyType
A body type that combines MIME type and encoding information.
ByteHeaderSource
A HeaderStore that kept the wire bytes of its fields, so a typed header can decode from them without a String in between.
ByteHeaderStore
A HeaderStore over the bytes of a request head.
Cache<K, V>
Abstract cache interface.
CacheBustingConfig
Cache-busting for asset URLs that embed a content hash.
CacheControlHeader
A class representing the HTTP Cache-Control header.
Cascade
A helper that calls several handlers in sequence and returns the first acceptable response.
ClearSiteDataHeader
A class representing the HTTP Clear-Site-Data header.
ClearSiteDataType
A class representing a single Clear-Site-Data type.
ConnectionHeader
A class representing the HTTP Connection header.
ConnectionHeaderType
A class representing the type of connection directives for the Connection header.
ConnectionInfo
Represents the connection information of a network request. Can be HTTP but also other types of network connections.
ContentDispositionHeader
A class representing the HTTP Content-Disposition header.
ContentDispositionParameter
A class representing a parameter for the Content-Disposition header.
ContentEncoding
A class representing valid content encodings.
ContentEncodingHeader
A class representing the HTTP Content-Encoding header.
ContentLanguageHeader
A class representing the HTTP Content-Language header.
ContentRangeHeader
A class representing an HTTP Content-Range header for byte ranges.
ContentSecurityPolicyDirective
A class representing a single CSP directive.
ContentSecurityPolicyHeader
A class representing the HTTP Content-Security-Policy (CSP) header.
ContentTypeHeader
A class representing the HTTP Content-Type header.
ContextProperty<T extends Object>
Manages a piece of data associated with a specific Request.
A class representing a single cookie.
CookieHeader
A class representing the HTTP Cookie header.
CrossOriginEmbedderPolicyHeader
A class representing the HTTP Cross-Origin-Embedder-Policy header.
CrossOriginOpenerPolicyHeader
A class representing the HTTP Cross-Origin-Opener-Policy header.
CrossOriginResourcePolicyHeader
A class representing the HTTP Cross-Origin-Resource-Policy header.
DeveloperTools
Developer tools for inspecting and debugging a RelicApp.
DigestAuthorizationHeader
Represents Digest authentication for HTTP Authorization.
DoubleFormField
A form field accessor that parses values as double.
DoublePathParam
A path parameter accessor that parses values as double.
DoubleQueryParam
A query parameter accessor that parses values as double.
EncodingQuality
A class representing an encoding with an optional quality value.
ETagConditionHeader
Base class for ETag-based conditional headers (If-Match and If-None-Match).
ETagHeader
A class representing the HTTP ETag header.
ETagValue
An HTTP entity-tag per RFC 9110 section 8.8.3.
ExpectHeader
A class representing the HTTP Expect header.
FileFieldEntry
A file field entry.
FileInfo
Cached file information including MIME type, file stats, and ETag.
FormData
Parsed HTML form data.
FormEntry
A single form entry.
FormField<T extends Object>
A read-only accessor for a typed form field.
FormFieldEntry
A text field entry.
FormFields
Text form fields, read through FormField accessors.
FormFile
A read-only accessor for an uploaded file.
FormLimits
Limits used while parsing HTML forms and multipart uploads.
ForwardedElement
Represents one forwarded-element in the Forwarded header.
ForwardedHeader
Typed representation of the Forwarded HTTP header. It's a list of ForwardedElements.
ForwardedIdentifier
Represents a node identifier in the Forwarded header, as per RFC 7239 Section 6. This can be an IP address (v4 or v6), "unknown", or an obfuscated identifier, optionally with a port.
FromHeader
A class representing the HTTP From header.
FunctionAccessor<T extends Object, K, R>
A ReadOnlyAccessor that decodes with a function.
HandlerObject
An abstract base class for classes that behave like Handlers.
HeaderAccessor<T extends Object>
A typed header, the HeaderName and the HeaderCodec that reads and writes it.
HeaderCodec<T extends Object>
A specialized codec for HTTP headers that defines conversion between a typed value T and its string representation in headers.
HeaderName
An interned HTTP header name.
Headers
Headers is an immutable, case-insensitive view over a HeaderStore.
HeaderScanner
A cursor-based scanner for HTTP header field values.
HeaderStore
Read access to the header fields of a message.
Hijack
A Result indicating that the underlying connection has been hijacked.
Host
An HTTP host reference per RFC 3986 section 3.2.2, used by Host headers, the Domain attribute of cookies, and the host=/for= values in Forwarded.
HostHeader
Wanna-be RFC3986 compliant 'Host' header.
IfMatchHeader
A class representing the HTTP If-Match header.
IfNoneMatchHeader
A class representing the HTTP If-None-Match header.
IfRangeHeader
A class representing the HTTP If-Range header.
InjectableIn<T>
Interface for objects that can be injected in others. This allows an object to delegate setup to another object.
IntFormField
A form field accessor that parses values as int.
IntPathParam
A path parameter accessor that parses values as int.
IntQueryParam
A query parameter accessor that parses values as int.
IOAdapter
An Adapter implementation for dart:io HttpServer.
IORelicWebSocket
A dart-io-based RelicWebSocket implementation.
IPAddress
Represents an IPv4 or IPv6 address, optionally with a CIDR prefix length.
IPv4Address
Represents an IPv4 address with optional CIDR prefix.
IPv6Address
Represents an IPv6 address with optional CIDR prefix.
IsolatedObject<T>
LanguageQuality
A class representing a language with an optional quality value.
LanguageTag
A BCP 47 language tag per RFC 5646, used by Content-Language (RFC 9110 8.5) and Accept-Language (RFC 9110 12.5.4).
Listener
One bound socket of an Adapter.
LookupResult<T extends Object>
Represents the result of looking up a route in the router.
LruCache<K, V>
A simple Least Recently Used (LRU) cache implementation.
MapHeaderStore
The reference MutableHeaderStore, a map from name to values.
MediaRange
A class representing a media range with an optional quality value.
MemoryUploadedFile
Uploaded file backed by memory.
MemoryUploadStorage
In-memory uploaded file storage.
Message
MethodMiss<T extends Object>
Indicates that a route exists for the path, but not for the HTTP method.
MiddlewareObject
An abstract base class for classes that behave like Middleware.
MimeType
A MIME type representing the format of content.
Miss<T extends Object>
Base class for lookup failures.
MultipartFieldPart
A named form-data part without a filename parameter.
MultipartFilePart
A named form-data part with a filename or filename* parameter, even an empty one.
MultipartFormData
Parsed multipart/form-data form data.
MultipartOtherPart
A part that is neither a MultipartFieldPart nor a MultipartFilePart, such as a part without a name or without form-data disposition.
MultipartPart
A streamed multipart form part.
MutableHeaders
The builder side of Headers, a MutableHeaderStore with typed reads and writes.
MutableHeaderStore
A HeaderStore that can be written.
NoCache<K, V>
A no-op Cache that never stores or retrieves values, for opting out of caching in high-cardinality workloads where it costs more than it saves.
NormalizedPath
Represents a URL path that has been normalized.
NumFormField
A form field accessor that parses values as num.
NumPathParam
A path parameter accessor that parses values as num.
NumQueryParam
A query parameter accessor that parses values as num.
OpaqueOrigin
The opaque origin sentinel, serialized as null.
Origin
A Web origin, as defined by the WHATWG Fetch Standard and RFC 6454.
ParameterValue
A parameter value for the token / quoted-string alternation used pervasively in HTTP headers (RFC 9110 5.6.6: parameters).
PathMiss<T extends Object>
Indicates that no route exists for the requested path.
PathParam<T extends Object>
A read-only accessor for extracting typed path parameters.
PathParameters
Holds path parameters extracted from a matched route.
PathTrie<T extends Object>
A Trie (prefix tree) data structure optimized for matching URL paths.
PermissionsPolicyDirective
A class representing a single Permissions-Policy directive.
PermissionsPolicyHeader
A class representing the HTTP Permissions-Policy header.
Pipeline
A helper that makes it easy to compose a set of Middleware and a Handler.
QueryParam<T extends Object>
A read-only accessor for extracting typed query parameters.
QueryParameters
Holds query parameters extracted from the request URL.
Range
A class representing a single range within a Range header.
RangeHeader
A class representing the HTTP Range header.
ReadOnlyAccessor<T extends Object, K, R>
A read-only accessor for extracting typed values from a keyed storage.
ReferrerPolicyHeader
A class representing the HTTP Referrer-Policy header.
RelicApp
RelicServer
RelicWebSocket
An relic specific interface for bi-directional communication over web-sockets.
Request
An HTTP request to be processed by a Relic Server application.
RequestFactory
Builds the Request for an AdapterExchange.
RequestTarget
The path and query of a request, as received.
Response
The response returned by a Handler.
Result
A sealed base class representing the result of handling a request.
RetryAfterHeader
A class representing the HTTP Retry-After header.
Router<T extends Object>
A URL router that maps path patterns to values of type T.
RouterMatch<T extends Object>
A successful route match: the route a request takes and what the path lookup extracted.
SameSite
Cookie cross-site availability configuration.
SecFetchDestHeader
A class representing the HTTP Sec-Fetch-Dest header.
SecFetchModeHeader
A class representing the HTTP Sec-Fetch-Mode header.
SecFetchSiteHeader
A class representing the HTTP Sec-Fetch-Site header.
SetCookie
A single HTTP Set-Cookie cookie: a name/value pair plus its attributes.
SetCookieHeader
The HTTP Set-Cookie response header: the ordered set of SetCookies a response sets.
StaticHandler
A HandlerObject that serves static files from a directory or a single file.
StrictTransportSecurityHeader
Represents the HTTP Strict-Transport-Security (HSTS) header for managing HSTS settings.
StringFormField
A form field accessor that returns the value as is.
TEHeader
A class representing the HTTP TE header.
TempUploadedFile
Uploaded file backed by a temp file on disk.
TempUploadStorage
Temp-file-backed upload storage for dart:io applications.
TeQuality
A class representing a transfer encoding with an optional quality value.
Token
An HTTP token value per RFC 9110 section 5.6.2.
Token68
An HTTP token68 value per RFC 7235 section 2.1.
TokenValue
A free-form Token value, validated at construction.
TransferEncoding
A class representing valid transfer encodings.
TransferEncodingHeader
A class representing the HTTP Transfer-Encoding header.
TrieMatch<T>
Represents the successfull result of a lookup.
TupleOrigin
A scheme://host[:port] origin tuple per RFC 6454.
UpgradeHeader
A class representing the HTTP Upgrade header.
UpgradeProtocol
A single protocol entry in an Upgrade header.
UploadedFile
A handle to an uploaded file.
UploadedFiles
Uploaded files, read through FormFile accessors.
UploadStorage
Storage backend for uploaded file parts.
UrlEncodedFormData
Parsed application/x-www-form-urlencoded form data.
VaryHeader
A class representing the HTTP Vary header.
WebSocketUpgrade
A Result indicating that a duplex stream connection (e.g., WebSocket) has been established.
XForwardedForHeader
Typed representation of the X-Forwarded-For (XFF) HTTP header.

Enums

ExchangeEnd
How an exchange finished.
FormLimit
A limit in FormLimits.
HttpProtocol
The HTTP version an exchange was received with.
LoggerType
Method
Represents the HTTP methods used in requests as constants.
Transport
The transport a Listener accepts connections on.

Mixins

AccessorStateMixin<K, R>
Typed reads over a keyed storage, with a cache of decoded values.

Extension Types

DeltaSeconds
A non-negative integer number of seconds, used by HTTP headers that carry delta-seconds values: Max-Age (RFC 9111 5.2.2.1, RFC 6265 5.2.2), Retry-After seconds form (RFC 9110 10.2.3), HSTS max-age (RFC 6797 6.1), and the second form of Retry-After.
SocketAddress

Extensions

CacheBustingFilenameExtension on CacheBustingConfig
DatetimeExtension on DateTime
Extensions on DateTime.
EventSinkEx on EventSink<T>
FormRequestExtension on Request
Form parsing helpers for Request.
ForwardingRequestEx on Request
HeadersEntries on Headers
The Map view the previous Headers had, for code that iterates it.
HeadersEx on HeaderValues
HttpResponseExtension on HttpResponse
Extension for io.HttpResponse to write the head from a framing.
LookupResultExtension on LookupResult<T>
Extension providing convenient type casting for LookupResult instances.
MiddlewareExtensions on Middleware
Extensions on Middleware to aid in composing Middleware and Handlers.
MutableHeadersEx on MutableHeaders
PathParametersRequestEx on Request
QueryParametersRequestEx on Request
RawEx on Map<K, R>
RelicAppIOServeEx on RelicApp
RouteEx on Router<T>
RouterHandlerEx on RelicRouter
Extension on RelicRouter that cater specifically to Handlers.
RoutingRequestEx on Request
Extension on Request providing access to routing information.
StreamEx on Stream<T>
Uint16ListConversionExtensions on Uint16List
Uint8ListConversionExtensions on Uint8List
UriEx on Uri
Extension methods for Uri used in tests and internal utilities.

Functions

bindHttpServer(InternetAddress address, {int port = 0, SecurityContext? context, int backlog = 0, bool v6Only = false, bool shared = false}) → Future<HttpServer>
Binds an HTTP server to the given address and port.
catchTopLevelErrors(void callback(), void onError(dynamic error, StackTrace)) → void
Run callback and capture any errors that would otherwise be top-leveled.
createMiddleware({FutureOr<Response?> onRequest(Request)?, FutureOr<Response> onResponse(Response)?, FutureOr<Response> onError(Object error, StackTrace)?}) → Middleware
Creates a Middleware using the provided functions.
encodeDate(DateTime d) → Iterable<String>
Encodes a DateTime to a iterable of string in HTTP date format.
encodeInt(int i) → Iterable<String>
Encode an integer to a iterable of string.
encodeMethod(Method m) → Iterable<String>
encodeMethodList(Iterable<Method> l) → Iterable<String>
Encode a list of methods to a iterable of string.
encodePositiveBool(bool b) → Iterable<String>
Encode a boolean to a iterable of string, if true.
encodePositiveInt(int i) → Iterable<String>
Encode a positive integer to a iterable of string, otherwise throws an error.
encodeString(String s) → Iterable<String>
Encode a string to a iterable of string.
encodeStringList(List<String> i) → Iterable<String>
Encode a list of strings to a iterable of string.
encodeUri(Uri uri) → Iterable<String>
Encode a Uri to a iterable of string.
getStaticFileInfo(File file, {MimeTypeResolver? mimeResolver}) → Future<FileInfo>
Public accessor for retrieving FileInfo for a given file.
httpDate() → String
The Date header value for now, an RFC 9110 5.6.7 IMF-fixdate.
joinHeaderValues(List<String>? values) → String?
Multiple header values are joined with commas. See https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-p1-messaging-21#page-22
logMessage(String message, {StackTrace? stackTrace, LoggerType type = LoggerType.info}) → void
Logs a message using print.
logRequests({Logger? logger}) → Middleware
Middleware which prints the time of the request, the elapsed time for the inner handlers, the response's status code and the request URI.
parseBool(String value) → bool
Parses a boolean from the given value and returns it as a bool.
parseDate(String value) → DateTime
Parses a date from the given value and returns it as a DateTime.
parseInt(String value) → int
Parses an integer from the given value and returns it as an int.
parseMethodSet(Iterable<String> values) → SplayTreeSet<Method>
Parses a list of methods from the given values and returns it as a List<Method>.
parseMethodSetFields(List<Uint8List> fields) → SplayTreeSet<Method>
parseMethodSet over the wire bytes of every field.
parsePositiveBool(String value) → bool
Parses a positive boolean from the given value and returns it as a bool.
parsePositiveInt(String value) → int
Parses a positive integer from the given value and returns it as an int.
parseString(String value) → String
Parses a string from the given value and returns it as a String.
parseStringList(Iterable<String> values) → List<String>
Parses a list of strings from the given values and returns it as a List<String>.
parseUri(String value) → Uri
Parses a URI from the given value and returns it as a Uri.
respondWith(Responder responder) → Handler
Creates a Handler that uses the given Responder function to generate a response.
routeWith<T extends Object>(Router<T> router, {bool backtrack = true, bool useHostWhenRouting = false, Handler toHandler(T)?}) → Middleware
Creates middleware that routes requests using the provided router.

Typedefs

CacheControlFactory = CacheControlHeader? Function(Request req, FileInfo fileInfo)
ConnectionsInfo = ({int active, int closing, int idle})
ExchangeSink = FutureOr<void> Function(AdapterExchange exchange)
The function an Adapter hands every exchange to.
Factory<T> = FutureOr<T> Function()
Handler = FutureOr<Result> Function(Request req)
A function that processes a Request to produce a Result.
HeaderValues = AccessorStateMixin<HeaderName, Iterable<String>>
Typed reads over header values, shared by Headers and MutableHeaders.
HijackCallback = void Function(StreamChannel<Uint8List>)
A callback function that handles a hijacked connection.
Logger = void Function(String message, {StackTrace? stackTrace, LoggerType type})
Middleware = Handler Function(Handler next)
A function which creates a new Handler by wrapping a Handler.
Parameters = Map<Symbol, String>
RawPathParam = String
RawQueryParam = String
RelicRouter = Router<Handler>
Just a typedef for better auto-complete ///
Responder = FutureOr<Response> Function(Request)
A simplified handler function that takes a Request and returns a Response.
RouterInjectable = InjectableIn<RelicRouter>
A contract for modular route registration in Relic applications.
WebSocketCallback = void Function(RelicWebSocket webSocket)
A callback function invoked when a socket connection is established.

Exceptions / Errors

FormException
Base exception for form parsing failures.
FormLimitExceededException
Exception thrown when a configured form parsing limit is exceeded.
HeaderException
HeaderException serves as the common supertype for specific exceptions that can occur when processing HTTP headers.
HijackRefused
What AdapterExchange.hijack throws for a request body the adapter decoded off the wire and the handler did not read to its end.
InvalidFormFieldException
Exception thrown when a form field value does not decode.
InvalidHeaderException
Exception thrown for invalid HTTP header values.
MalformedFormDataException
Exception thrown when form data is malformed.
MaxBodySizeExceeded
Exception thrown when the body size exceeds the maximum allowed length.
MissingFormFieldException
Exception thrown when a required form field or file is absent.
MissingHeaderException
Exception thrown when a required HTTP header is missing.
UnsupportedFormMediaTypeException
Exception thrown when a request media type is unsupported for form parsing.