Skip to content

Go API Reference

Go API Reference v0.17.1

Functions

SchemaQueryOnly()

Create a simple schema configuration with only Query type.

This is a convenience function for schemas that only have queries.

Returns:

A QueryOnlyConfig with default settings

Signature:

func SchemaQueryOnly() *QueryOnlyConfig

Example:

result := SchemaQueryOnly()

Returns: QueryOnlyConfig


SchemaQueryMutation()

Create a schema configuration with Query and Mutation types.

This is a convenience function for schemas with queries and mutations but no subscriptions.

Returns:

A QueryMutationConfig with default settings

Signature:

func SchemaQueryMutation() *QueryMutationConfig

Example:

result := SchemaQueryMutation()

Returns: QueryMutationConfig


SchemaFull()

Create a schema configuration with all three root types.

This is a convenience function for fully-featured schemas.

Returns:

A FullSchemaConfig with default settings

Signature:

func SchemaFull() *FullSchemaConfig

Example:

result := SchemaFull()

Returns: FullSchemaConfig


Types

ApiKeyAuthConfig

Per-route API key authentication requirement.

Mirrors spikard_http.ApiKeyConfig for the same reason JwtAuthConfig mirrors spikard_http.JwtConfig: spikard-core cannot depend on spikard-http.

Field Type Default Description
Enabled bool true Whether this per-route API key auth requirement is active. Present on 10/10 api_key_auth fixture payloads in the corpus; defaults to true for the same reason as JwtAuthConfig.enabled.
Keys \[\]string /* serde(default) */ Valid API keys. Defaults to empty (rather than being a required field) so that fixtures/server_config.json's server_jwt_and_api_key_auth_combined payload ({"enabled": true, "header": "X-API-Key"}, no keys at all) deserializes instead of hard-failing with "missing field keys". An empty list is NOT "allow everyone": a later enforcement phase MUST treat an empty keys list as a hard misconfiguration error, never as an open gate.
HeaderName string "X-API-Key" Header name to check (e.g., "X-API-Key")

ApiKeyConfig

API Key authentication configuration

Field Type Default Description
Keys \[\]string — Valid API keys
HeaderName string "X-API-Key" Header name to check (e.g., "X-API-Key")

AsyncApiConfig

AsyncAPI HTTP endpoint configuration

Field Type Default Description
Enabled bool — Enable AsyncAPI endpoints (default: false)
Spec *interface{} nil Pre-registered AsyncAPI spec to serve from GET /asyncapi.json

AuthorizationConfig

Per-route roles/scopes/permissions authorization requirement.

spikard_http.auth.Claims does not yet carry roles, scopes, or permissions, so nothing can enforce this today. This type only defines the requirement shape; a later phase must extend Claims (or an equivalent claims-decoding path) to populate them before enforcement is possible.

Deserialization goes through AuthorizationConfigRepr rather than a derive so the fixture's singular {"required_role": "admin"} shape (fixtures/problem_details.json's problem_details_403_forbidden) populates required_roles instead of being silently dropped as an unrecognized field — a config that parses to "no constraint" from real authorization data is a vacuous-pass bug, not a compatibility shim. deny_unknown_fields on the repr means any other unrecognized key is a loud deserialize error instead.

Field Type Default Description
RequiredRoles \[\]string nil Roles the authenticated caller must have
RequiredScopes \[\]string nil OAuth-style scopes the authenticated caller must have
RequiredPermissions \[\]string nil Fine-grained permissions the authenticated caller must have
RequireAll bool true When true, the caller must satisfy every listed requirement (AND); when false, any single listed requirement is sufficient (OR)

BackgroundJobMetadata

Field Type Default Description
Name string "background_task" The name
RequestId *string nil Request id

BackgroundTaskConfig

Configuration for in-process background task execution.

Field Type Default Description
Enabled bool false Whether the server starts a background task executor at router-construction time. ServerConfig.background_tasks is a bare struct rather than an Option, so its mere presence cannot mean "configured" the way Option-shaped middleware config does — every server has one. Without this flag every router build would spawn an executor task, which also requires an ambient Tokio runtime that a synchronous build_router_* caller may not have. Defaults to false so opting in is explicit, and matches the corpus vocabulary: fixtures/background_tasks.json spells its per-route payloads {"enabled": true, ...}.
MaxQueueSize uint 1024 Maximum queue size
MaxConcurrentTasks uint 128 Maximum concurrent tasks
DrainTimeoutSecs uint64 30 Drain timeout secs

CompressionConfig

Compression configuration shared across runtimes

Field Type Default Description
Gzip bool true Enable gzip compression
Brotli bool true Enable brotli compression
MinSize uint 1024 Minimum response size to compress (bytes)
Quality uint32 6 Compression quality (0-11 for brotli, 0-9 for gzip)

ContactInfo

Contact information

Field Type Default Description
Name *string nil Name of the contact person or organisation.
Email *string nil Contact email address.
Url *string nil URL pointing to the contact information page.

CorsConfig

CORS configuration for a route

Field Type Default Description
AllowedOrigins \[\]string ["*"] Allowed origins
AllowedMethods \[\]string ["*"] Allowed methods
AllowedHeaders \[\]string nil Allowed headers
ExposeHeaders *\[\]string nil Expose headers
MaxAge *uint32 nil Maximum age
AllowCredentials *bool nil Allow credentials
Methods
AllowedMethodsJoined()

Get the cached joined methods string for preflight responses

Signature:

func (o *CorsConfig) AllowedMethodsJoined() string

Example:

result := instance.AllowedMethodsJoined()

Returns: string

AllowedHeadersJoined()

Get the cached joined headers string for preflight responses

Signature:

func (o *CorsConfig) AllowedHeadersJoined() string

Example:

result := instance.AllowedHeadersJoined()

Returns: string

IsOriginAllowed()

Check if an origin is allowed (O(1) with wildcard, O(n) for exact match)

Signature:

func (o *CorsConfig) IsOriginAllowed(origin string) bool

Example:

result := instance.IsOriginAllowed("value")

Parameters:

Name Type Required Description
Origin string Yes The origin

Returns: bool

IsMethodAllowed()

Check if a method is allowed (O(1) with wildcard, O(n) for exact match)

Signature:

func (o *CorsConfig) IsMethodAllowed(method string) bool

Example:

result := instance.IsMethodAllowed("value")

Parameters:

Name Type Required Description
Method string Yes The method

Returns: bool


DynamicSchemaConfig

Configuration for building and executing a dynamic-SDL schema.

Field Type Default Description
IntrospectionEnabled bool — Whether introspection queries (__schema, __type) are permitted.
MaxComplexity *uint nil Maximum query complexity (nil = unlimited).
MaxDepth *uint nil Maximum query depth (nil = unlimited).
FieldErrors \[\]FieldErrorSpec nil Field-level errors to inject at specific response paths.

FieldErrorSpec

A field-level error to inject at a specific response path.

path is the dot-separated sequence of field names from the operation root to the field that should fail, e.g. "user" for a top-level field or "order.customer" for a nested one.

Field Type Default Description
Path string — Dot-separated path to the field that should error.
Message string — The error message to surface for that field.

FullSchemaConfig

Configuration for fully-featured schemas with Query, Mutation, and Subscription types

Field Type Default Description
IntrospectionEnabled bool true Enable introspection queries
ComplexityLimit *uint nil Maximum query complexity (None = unlimited)
DepthLimit *uint nil Maximum query depth (None = unlimited)

GraphQlRouteConfig

Configuration for GraphQL routes

Provides a builder pattern for configuring GraphQL route parameters for the Spikard HTTP server's routing system.

Methods
New()

Create a new GraphQL route configuration with defaults

Default values:

  • path: "/graphql"
  • method: "POST"
  • enable_playground: false

Signature:

func GraphQlRouteConfigNew() *GraphQlRouteConfig

Example:

result := GraphQlRouteConfigNew()

Returns: GraphQlRouteConfig

Path()

Set the HTTP path for the GraphQL endpoint

Signature:

func (o *GraphQlRouteConfig) Path(path string) *GraphQlRouteConfig

Example:

result := instance.Path("value")

Parameters:

Name Type Required Description
Path string Yes The URL path (e.g., "/graphql", "/api/graphql")

Returns: GraphQlRouteConfig

Method()

Set the HTTP method for the GraphQL endpoint

Signature:

func (o *GraphQlRouteConfig) Method(method string) *GraphQlRouteConfig

Example:

result := instance.Method("value")

Parameters:

Name Type Required Description
Method string Yes The HTTP method (typically "POST")

Returns: GraphQlRouteConfig

EnablePlayground()

Enable or disable the GraphQL Playground UI

Signature:

func (o *GraphQlRouteConfig) EnablePlayground(enable bool) *GraphQlRouteConfig

Example:

result := instance.EnablePlayground(true)

Parameters:

Name Type Required Description
Enable bool Yes Whether to enable playground

Returns: GraphQlRouteConfig

Description()

Set a custom description for documentation

Signature:

func (o *GraphQlRouteConfig) Description(description string) *GraphQlRouteConfig

Example:

result := instance.Description("value")

Parameters:

Name Type Required Description
Description string Yes Documentation string

Returns: GraphQlRouteConfig

GetPath()

Get the configured path

Signature:

func (o *GraphQlRouteConfig) GetPath() string

Example:

result := instance.GetPath()

Returns: string

GetMethod()

Get the configured method

Signature:

func (o *GraphQlRouteConfig) GetMethod() string

Example:

result := instance.GetMethod()

Returns: string

IsPlaygroundEnabled()

Check if playground is enabled

Signature:

func (o *GraphQlRouteConfig) IsPlaygroundEnabled() bool

Example:

result := instance.IsPlaygroundEnabled()

Returns: bool

GetDescription()

Get the description if set

Signature:

func (o *GraphQlRouteConfig) GetDescription() *string

Example:

result := instance.GetDescription()

Returns: *string


GrpcConfig

Configuration for gRPC support

Controls how the server handles gRPC requests, including compression, timeouts, and protocol settings.

Stream Limits

This configuration enforces message-level size limits but delegates concurrent stream limiting to the HTTP/2 transport layer:

  • Message Size Limits: The max_message_size field is enforced per individual message (request or response) in both unary and streaming RPCs. When a single message exceeds this limit, the request is rejected with PAYLOAD_TOO_LARGE (HTTP 413).

  • Concurrent Stream Limits: The max_concurrent_streams is an advisory configuration passed to the HTTP/2 layer for connection-level stream negotiation. The HTTP/2 transport automatically enforces this limit and returns GOAWAY frames when exceeded. Applications should not rely on custom enforcement of this limit.

  • Stream Response Size Limits: The max_stream_response_bytes field caps the total encoded bytes emitted across a server-streaming or bidi-streaming response. When the cumulative size exceeds the limit, the stream is terminated with tonic.Status.resource_exhausted. Defaults to nil (unbounded).

Field Type Default Description
Enabled bool true Enable gRPC support
MaxMessageSize uint 4194304 Maximum message size in bytes (for both sending and receiving) This limit applies to individual messages in both unary and streaming RPCs. When a single message exceeds this size, the request is rejected with HTTP 413 (Payload Too Large). Default: 4MB (4194304 bytes) Note: This limit does NOT apply to the total response size in streaming RPCs. For multi-message streams, the total response can exceed this limit as long as each individual message stays within the limit.
EnableCompression bool true Enable gzip compression for gRPC messages
RequestTimeout *uint64 nil Timeout for gRPC requests in seconds (None = no timeout)
MaxConcurrentStreams uint32 100 Maximum number of concurrent streams per connection (HTTP/2 advisory) This value is communicated to HTTP/2 clients as the server's flow control limit. The HTTP/2 transport layer enforces this limit automatically via SETTINGS frames and GOAWAY responses. Applications should NOT implement custom enforcement. Default: 100 streams per connection # Stream Limiting Strategy - Per Connection: This limit applies per HTTP/2 connection, not globally - Transport Enforcement: HTTP/2 handles all stream limiting; applications need not implement custom checks - Streaming Requests: In server streaming or bidi streaming, each logical RPC consumes one stream slot. Message ordering within a stream follows HTTP/2 frame ordering.
EnableKeepalive bool true Enable HTTP/2 keepalive
KeepaliveInterval uint64 75 HTTP/2 keepalive interval in seconds
KeepaliveTimeout uint64 20 HTTP/2 keepalive timeout in seconds
MaxStreamResponseBytes *uint nil Total byte cap across an entire streaming response. When Some(n), the streaming adapter aborts the stream with tonic.Status.resource_exhausted once the cumulative encoded message bytes exceed n. The stream yields the error item and then terminates. Per-message cap remains max_message_size. This limit applies to server-streaming and bidirectional-streaming RPCs only; unary RPCs are governed solely by max_message_size. Default: nil (unbounded total response size).

IntoHandler

Convert user-facing handler functions into the low-level Handler trait.

Methods
IntoHandler()

Convert this value into a shared request handler.

Signature:

func (o *IntoHandler) IntoHandler() *Handler

Example:

result := instance.IntoHandler()

Returns: Handler


JsonRpcConfig

JSON-RPC server configuration

Field Type Default Description
Enabled bool true Enable JSON-RPC endpoint
EndpointPath string "/rpc" HTTP endpoint path for JSON-RPC requests (default: "/rpc")
EnableBatch bool true Enable batch request processing (default: true)
MaxBatchSize uint 100 Maximum number of requests in a batch (default: 100)

JsonRpcMethodInfo

JSON-RPC method metadata for routes that support JSON-RPC

This struct captures the metadata needed to expose HTTP routes as JSON-RPC methods, enabling discovery and documentation of RPC-compatible endpoints.

Field Type Default Description
MethodName string — The JSON-RPC method name (e.g., "user.create")
Description *string nil Optional description of what the method does
ParamsSchema *interface{} nil Optional JSON Schema for method parameters
ResultSchema *interface{} nil Optional JSON Schema for the result
Deprecated bool /* serde(default) */ Whether this method is deprecated
Tags \[\]string /* serde(default) */ Tags for categorizing and grouping methods

JwtAuthConfig

Per-route JWT authentication requirement.

spikard-http defines the canonical JwtConfig used by ServerConfig.jwt_auth, but spikard-core cannot depend on spikard-http (the dependency runs the other way), so that type cannot be reused here. This mirrors its fields so a later enforcement phase in spikard-http can convert between the two without losing information.

secret and public_key are both optional because asymmetric algorithms (RS256, ES256, ...) verify against a public key rather than a shared secret; see fixtures/auth.json's jwt_config_algorithm_rs256, which carries public_key and no secret at all. Exactly one is expected to be populated for a given algorithm, but that cross-field invariant is left to a later enforcement phase rather than the type itself.

Field Type Default Description
Enabled bool true Whether this per-route JWT auth requirement is active. Present on 21/21 jwt_auth fixture payloads in the corpus; defaults to true because presence of a jwt_auth block has always meant "enabled" up to now. Without this field a fixture setting "enabled": false would silently keep auth on while the fixture's parse still succeeds — a vacuous pass.
Secret *string /* serde(default) */ Symmetric secret key for JWT verification (HS256, HS384, HS512)
PublicKey *string /* serde(default) */ Asymmetric public key for JWT verification (RS256, ES256, etc.)
Algorithm string "HS256" Required algorithm (HS256, HS384, HS512, RS256, etc.)
Audience *\[\]string nil Required audience claim
Issuer *string nil Required issuer claim
Leeway uint64 /* serde(default) */ Leeway for expiration checks (seconds)

JwtConfig

JWT authentication configuration

Field Type Default Description
Secret string — Secret key for JWT verification
Algorithm string "HS256" Required algorithm (HS256, HS384, HS512, RS256, etc.)
Audience *\[\]string nil Required audience claim
Issuer *string nil Required issuer claim
Leeway uint64 /* serde(default) */ Leeway for expiration checks (seconds)

LicenseInfo

License information

Field Type Default Description
Name string — SPDX license identifier or display name (e.g. "MIT").
Url *string nil URL to the full license text.

LifecycleHookRef

A single lifecycle hook reference within a LifecycleHooksConfig phase.

Matches the fixture shape exactly (fixtures/lifecycle_hooks.json, fixtures/di.json): each entry is an object with a required name and handler, an optional list of dependency keys, and an optional free-form config blob (e.g. {"max_requests": 10, "window_seconds": 60} for a rate-limiting hook). deny_unknown_fields turns future fixture drift into a loud error.

Field Type Default Description
Name string — Registered name of the hook to run, resolved against the server's LifecycleHooks
Handler string — Name of the handler function this hook invokes
Dependencies \[\]string nil Dependency keys this hook requires (for DI), resolved before the hook runs
Config *interface{} nil Optional free-form configuration passed to the hook (e.g. rate-limit thresholds)
Order *uint32 nil Explicit execution order within the phase, where the corpus states one (fixtures/lifecycle_hooks.json's hook_execution_order). Array position already implies an order, so this exists to let a fixture assert ordering rather than rely on it.

LifecycleHooksConfig

Per-route selection of registered lifecycle hooks.

ServerConfig.lifecycle_hooks holds Arc<dyn LifecycleHook> function pointers and is marked #[serde(skip)] / #[alef(skip)] because closures cannot be serialized or cross the FFI boundary. A per-route field with that same shape would be invisible to alef, and therefore invisible to every binding — defeating the purpose of exposing it here. This descriptor carries LifecycleHookRef entries instead: each one names a registered hook (plus its declared dependencies and optional config), so a later enforcement phase can resolve those names against the server's registered LifecycleHooks and run the matches for this route. The five fields mirror the five hook phases documented in the tower-middleware-and-lifecycle project convention (onRequest, preValidation, preHandler, onResponse, onError).

Field Type Default Description
OnRequest \[\]LifecycleHookRef nil Hooks to run in the on_request phase
PreValidation \[\]LifecycleHookRef nil Hooks to run in the pre_validation phase
PreHandler \[\]LifecycleHookRef nil Hooks to run in the pre_handler phase
OnResponse \[\]LifecycleHookRef nil Hooks to run in the on_response phase
OnError \[\]LifecycleHookRef nil Hooks to run in the on_error phase

OpenApiConfig

OpenAPI configuration

Field Type Default Description
Enabled bool false Enable OpenAPI generation (default: false for zero overhead)
Title string "API" API title
Version string "1.0.0" API version
Description *string nil API description (supports markdown)
SwaggerUiPath string "/docs" Path to serve Swagger UI (default: "/docs")
RedocPath string "/redoc" Path to serve Redoc (default: "/redoc")
OpenapiJsonPath string "/openapi.json" Path to serve OpenAPI JSON spec (default: "/openapi.json")
Contact *ContactInfo nil Contact information
License *LicenseInfo nil License information
Servers \[\]ServerInfo nil Server definitions
SecuritySchemes map\[string\]SecuritySchemeInfo nil Security schemes (auto-detected from middleware if not provided)

ParseRequest

Request body for POST /asyncapi/parse

Field Type Default Description
Spec interface{} — Spec

ParseResult

Full parse result returned by POST /asyncapi/parse

Field Type Default Description
SpecVersion string — Spec version
Title string — Title
ApiVersion string — Api version
Channels \[\]ParsedChannel — Channels
Operations \[\]ParsedOperation — Operations
Messages \[\]ParsedMessage — Messages

ParsedChannel

A single channel extracted from an AsyncAPI spec

Field Type Default Description
Name string — Channel key from the spec (e.g. "chat/messages")
Address string — Channel address / path
Messages \[\]string — Message names declared on this channel
Bindings *interface{} nil Bindings (ws / http / amqp / …) as raw JSON for forward-compatibility

ParsedMessage

A resolved message (name + JSON Schema)

Field Type Default Description
Name string — Message name
Schema *interface{} nil Resolved JSON Schema for the message payload, if available

ParsedOperation

A single operation extracted from an AsyncAPI spec

Field Type Default Description
Name string — Operation name
Action string — Operation action: "send" or "receive"
Channel string — Channel reference (resolved to the channel name)

ProblemDetails

RFC 9457 Problem Details for HTTP APIs

A machine-readable format for specifying errors in HTTP API responses. Per RFC 9457, all fields are optional. The type field defaults to "about:blank" if not specified.

Content-Type

Responses using this struct should set:

Content-Type: application/problem+json
{
  "type": "<https://spikard.dev/errors/validation-error>",
  "title": "Request Validation Failed",
  "status": 422,
  "detail": "2 validation errors in request body",
  "errors": [...]
}
Field Type Default Description
TypeUri string "about:blank" A URI reference that identifies the problem type. Defaults to "about:blank" when absent. Should be a stable, human-readable identifier for the problem type.
Title string "" A short, human-readable summary of the problem type. Should not change from occurrence to occurrence of the problem.
Status uint16 500 The HTTP status code generated by the origin server. This is advisory; the actual HTTP status code takes precedence.
Detail *string nil A human-readable explanation specific to this occurrence of the problem.
Instance *string nil A URI reference that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced.
Extensions map\[string\]interface{} nil Extension members - problem-type-specific data. For validation errors, this typically contains an "errors" array.
Methods
WithDetail()

Set the detail field

Signature:

func (o *ProblemDetails) WithDetail(detail string) *ProblemDetails

Example:

result := instance.WithDetail("value")

Parameters:

Name Type Required Description
Detail string Yes The detail

Returns: ProblemDetails

WithInstance()

Set the instance field

Signature:

func (o *ProblemDetails) WithInstance(instance string) *ProblemDetails

Example:

result := instance.WithInstance("value")

Parameters:

Name Type Required Description
Instance string Yes The instance

Returns: ProblemDetails

NotFound()

Create a not found error

Signature:

func ProblemDetailsNotFound(detail string) *ProblemDetails

Example:

result := ProblemDetailsNotFound("value")

Parameters:

Name Type Required Description
Detail string Yes The detail

Returns: ProblemDetails

MethodNotAllowed()

Create a method not allowed error

Signature:

func ProblemDetailsMethodNotAllowed(detail string) *ProblemDetails

Example:

result := ProblemDetailsMethodNotAllowed("value")

Parameters:

Name Type Required Description
Detail string Yes The detail

Returns: ProblemDetails

InternalServerError()

Create an internal server error

Signature:

func ProblemDetailsInternalServerError(detail string) *ProblemDetails

Example:

result := ProblemDetailsInternalServerError("value")

Parameters:

Name Type Required Description
Detail string Yes The detail

Returns: ProblemDetails

BadRequest()

Create a bad request error

Signature:

func ProblemDetailsBadRequest(detail string) *ProblemDetails

Example:

result := ProblemDetailsBadRequest("value")

Parameters:

Name Type Required Description
Detail string Yes The detail

Returns: ProblemDetails

ToJson()

Serialize to JSON string

Errors: Returns an error if the serialization fails.

Signature:

func (o *ProblemDetails) ToJson() (string, error)

Example:

result, err := instance.ToJson()
if err != nil {
    return err
}

Returns: string

Errors: Returns error.

ToJsonPretty()

Serialize to pretty JSON string

Errors: Returns an error if the serialization fails.

Signature:

func (o *ProblemDetails) ToJsonPretty() (string, error)

Example:

result, err := instance.ToJsonPretty()
if err != nil {
    return err
}

Returns: string

Errors: Returns error.


QueryMutationConfig

Configuration for schemas with Query and Mutation types

Field Type Default Description
IntrospectionEnabled bool true Enable introspection queries
ComplexityLimit *uint nil Maximum query complexity (None = unlimited)
DepthLimit *uint nil Maximum query depth (None = unlimited)

QueryOnlyConfig

Configuration for schemas with only Query type

Field Type Default Description
IntrospectionEnabled bool true Enable introspection queries
ComplexityLimit *uint nil Maximum query complexity (None = unlimited)
DepthLimit *uint nil Maximum query depth (None = unlimited)

RateLimitConfig

Rate limiting configuration shared across runtimes

Field Type Default Description
PerSecond uint64 100 Requests per second
Burst uint32 200 Burst allowance
IpBased bool true Use IP-based rate limiting

Request


RequestIdConfig

Per-route request-id generation/propagation override.

Modeled as a struct rather than Option<bool> on RouteMetadata because the wire shape is an object, not a bare boolean: fixtures/request_id.json's request_id_middleware_can_be_disabled sends {"enabled": false}, which Option<bool> cannot deserialize at all ("invalid type: map, expected a boolean") — the very fixture whose purpose is proving the middleware can be disabled was the one that failed to parse.

Field Type Default Description
Enabled bool — Whether request-id generation/propagation is active for this route

Response

HTTP Response with custom status code, headers, and content

Field Type Default Description
Content *interface{} nil Response body content
StatusCode uint16 200 HTTP status code (defaults to 200)
Headers map\[string\]string nil Response headers
Methods
SetHeader()

Set a header

Signature:

func (o *Response) SetHeader(key string, value string)

Example:

instance.SetHeader("value", "value")

Parameters:

Name Type Required Description
Key string Yes The key
Value string Yes The value

Returns: No return value.

SetCookie()

Set a cookie in the response

Signature:

func (o *Response) SetCookie(key string, value string, secure bool, httpOnly bool, maxAge int64, domain string, path string, sameSite string)

Example:

instance.SetCookie("value", "value", true, true, 42, "value", "value", "value")

Parameters:

Name Type Required Description
Key string Yes The key
Value string Yes The value
Secure bool Yes The secure
HttpOnly bool Yes The http only
MaxAge *int64 No The max age
Domain *string No The domain
Path *string No Path to the file
SameSite *string No The same site

Returns: No return value.


RouteBuilder

Builder for defining a route.

Methods
New()

Create a new builder for the provided HTTP method and path.

Signature:

func RouteBuilderNew(method Method, path string) *RouteBuilder

Example:

result := RouteBuilderNew(Method{}, "value")

Parameters:

Name Type Required Description
Method Method Yes The method
Path string Yes Path to the file

Returns: RouteBuilder

HandlerName()

Assign an explicit handler name.

Signature:

func (o *RouteBuilder) HandlerName(name string) *RouteBuilder

Example:

result := instance.HandlerName("value")

Parameters:

Name Type Required Description
Name string Yes The name

Returns: RouteBuilder

RequestSchemaJson()

Provide a raw JSON schema for the request body.

Signature:

func (o *RouteBuilder) RequestSchemaJson(schema interface{}) *RouteBuilder

Example:

result := instance.RequestSchemaJson(nil)

Parameters:

Name Type Required Description
Schema interface{} Yes The schema

Returns: RouteBuilder

ResponseSchemaJson()

Provide a raw JSON schema for the response body.

Signature:

func (o *RouteBuilder) ResponseSchemaJson(schema interface{}) *RouteBuilder

Example:

result := instance.ResponseSchemaJson(nil)

Parameters:

Name Type Required Description
Schema interface{} Yes The schema

Returns: RouteBuilder

ParamsSchemaJson()

Provide a raw JSON schema for request parameters.

Signature:

func (o *RouteBuilder) ParamsSchemaJson(schema interface{}) *RouteBuilder

Example:

result := instance.ParamsSchemaJson(nil)

Parameters:

Name Type Required Description
Schema interface{} Yes The schema

Returns: RouteBuilder

FileParamsJson()

Provide multipart file parameter configuration.

Signature:

func (o *RouteBuilder) FileParamsJson(schema interface{}) *RouteBuilder

Example:

result := instance.FileParamsJson(nil)

Parameters:

Name Type Required Description
Schema interface{} Yes The schema

Returns: RouteBuilder

Cors()

Attach a CORS configuration for this route.

Signature:

func (o *RouteBuilder) Cors(cors CorsConfig) *RouteBuilder

Example:

result := instance.Cors(CorsConfig{})

Parameters:

Name Type Required Description
Cors CorsConfig Yes The cors config

Returns: RouteBuilder

Compression()

Attach a compression configuration for this route.

Signature:

func (o *RouteBuilder) Compression(compression CompressionConfig) *RouteBuilder

Example:

result := instance.Compression(CompressionConfig{})

Parameters:

Name Type Required Description
Compression CompressionConfig Yes The compression config

Returns: RouteBuilder

BodyLimit()

Attach a per-route maximum request body size in bytes, overriding the server-global default.

Signature:

func (o *RouteBuilder) BodyLimit(maxBytes uint) *RouteBuilder

Example:

result := instance.BodyLimit(42)

Parameters:

Name Type Required Description
MaxBytes uint Yes The max bytes

Returns: RouteBuilder

RequestTimeout()

Attach a per-route request timeout in seconds, overriding the server-global default.

Signature:

func (o *RouteBuilder) RequestTimeout(seconds uint64) *RouteBuilder

Example:

result := instance.RequestTimeout(42)

Parameters:

Name Type Required Description
Seconds uint64 Yes The seconds

Returns: RouteBuilder

RateLimit()

Attach a per-route rate limiting configuration, overriding the server-global default.

Signature:

func (o *RouteBuilder) RateLimit(rateLimit RateLimitConfig) *RouteBuilder

Example:

result := instance.RateLimit(RateLimitConfig{})

Parameters:

Name Type Required Description
RateLimit RateLimitConfig Yes The rate limit config

Returns: RouteBuilder

RequestId()

Force per-route request-id generation on or off, overriding the server-global default.

Takes a plain bool rather than RequestIdConfig directly: the wire/metadata type had to become a struct to represent {"enabled": false} (see RequestIdConfig's docs), but this builder is the ergonomic call site (.request_id(true)), so it keeps accepting a bool and wraps it into RequestIdConfig internally in Self.into_metadata.

Signature:

func (o *RouteBuilder) RequestId(enabled bool) *RouteBuilder

Example:

result := instance.RequestId(true)

Parameters:

Name Type Required Description
Enabled bool Yes The enabled

Returns: RouteBuilder

JwtAuth()

Require JWT authentication for this route.

Signature:

func (o *RouteBuilder) JwtAuth(config JwtAuthConfig) *RouteBuilder

Example:

result := instance.JwtAuth(JwtAuthConfig{})

Parameters:

Name Type Required Description
Config JwtAuthConfig Yes The configuration options

Returns: RouteBuilder

ApiKeyAuth()

Require API key authentication for this route.

Signature:

func (o *RouteBuilder) ApiKeyAuth(config ApiKeyAuthConfig) *RouteBuilder

Example:

result := instance.ApiKeyAuth(ApiKeyAuthConfig{})

Parameters:

Name Type Required Description
Config ApiKeyAuthConfig Yes The configuration options

Returns: RouteBuilder

Authorization()

Attach a roles/scopes/permissions authorization requirement for this route.

Signature:

func (o *RouteBuilder) Authorization(config AuthorizationConfig) *RouteBuilder

Example:

result := instance.Authorization(AuthorizationConfig{})

Parameters:

Name Type Required Description
Config AuthorizationConfig Yes The configuration options

Returns: RouteBuilder

LifecycleHooks()

Select registered lifecycle hooks to run for this route.

Signature:

func (o *RouteBuilder) LifecycleHooks(hooks LifecycleHooksConfig) *RouteBuilder

Example:

result := instance.LifecycleHooks(LifecycleHooksConfig{})

Parameters:

Name Type Required Description
Hooks LifecycleHooksConfig Yes The lifecycle hooks config

Returns: RouteBuilder

JsonrpcMethod()

Expose this route as a JSON-RPC method.

Signature:

func (o *RouteBuilder) JsonrpcMethod(info JsonRpcMethodInfo) *RouteBuilder

Example:

result := instance.JsonrpcMethod(JsonRpcMethodInfo{})

Parameters:

Name Type Required Description
Info JsonRpcMethodInfo Yes The json rpc method info

Returns: RouteBuilder

OpenrpcSpec()

Attach a literal OpenRPC method spec document for this route, overriding auto-derivation from the Self.jsonrpc_method metadata when present.

Signature:

func (o *RouteBuilder) OpenrpcSpec(spec interface{}) *RouteBuilder

Example:

result := instance.OpenrpcSpec(nil)

Parameters:

Name Type Required Description
Spec interface{} Yes The spec

Returns: RouteBuilder

Sync()

Mark the route as synchronous.

Signature:

func (o *RouteBuilder) Sync() *RouteBuilder

Example:

result := instance.Sync()

Returns: RouteBuilder

HandlerDependencies()

Declare the dependency keys that must be resolved before this handler runs.

Signature:

func (o *RouteBuilder) HandlerDependencies(dependencies []string) *RouteBuilder

Example:

result := instance.HandlerDependencies(nil)

Parameters:

Name Type Required Description
Dependencies \[\]string Yes The dependencies

Returns: RouteBuilder


SchemaConfig

Configuration for GraphQL schema building.

Encapsulates all schema-level configuration options including introspection control, complexity limits, and depth limits.

Field Type Default Description
IntrospectionEnabled bool true Enable introspection queries
ComplexityLimit *uint nil Maximum query complexity (None = unlimited)
DepthLimit *uint nil Maximum query depth (None = unlimited)

ServerConfig

Server configuration

Field Type Default Description
Host string "127.0.0.1" Host to bind to
Port uint16 8000 Port to bind to
Workers uint 1 Number of Tokio runtime worker threads used by binding-managed server runtimes
EnableRequestId bool false Enable request ID generation and propagation
MaxBodySize *uint 10485760 Maximum request body size in bytes (None = unlimited, not recommended)
RequestTimeout *uint64 nil Request timeout in seconds (None = no timeout)
Compression *CompressionConfig nil Enable compression middleware
RateLimit *RateLimitConfig nil Enable rate limiting
JwtAuth *JwtConfig nil JWT authentication configuration
ApiKeyAuth *ApiKeyConfig nil API Key authentication configuration
StaticFiles \[\]StaticFilesConfig nil Static file serving configuration
GracefulShutdown bool true Enable graceful shutdown on SIGTERM/SIGINT
ShutdownTimeout uint64 30 Graceful shutdown timeout (seconds)
Asyncapi *AsyncApiConfig nil AsyncAPI HTTP endpoint configuration
Openapi *OpenApiConfig nil OpenAPI documentation configuration
Jsonrpc *JsonRpcConfig nil JSON-RPC configuration
Grpc *GrpcConfig nil gRPC configuration
BackgroundTasks BackgroundTaskConfig — Background task executor configuration
EnableHttpTrace bool false Enable per-request HTTP tracing (tower-http TraceLayer)

ServerInfo

Server information

Field Type Default Description
Url string — Base URL of the server (e.g. "<https://api.example.com/v1>").
Description *string nil Optional human-readable description of the server environment.

SseEvent

An individual SSE event

Represents a single Server-Sent Event to be sent to a connected client. Events can have an optional type, ID, and retry timeout for advanced scenarios.

SSE Format

Events are serialized to the following text format:

event: event_type
data: {"json":"value"}
id: event-123
retry: 3000
Field Type Default Description
EventType *string nil Event type (optional)
Data interface{} — Event data (JSON value)
Id *string nil Event ID (optional, for client-side reconnection)
Retry *uint64 nil Retry timeout in milliseconds (optional)
Methods
WithId()

Set the event ID for client-side reconnection support

Sets an ID that clients can use to resume from this point if they disconnect. The client sends this ID back in the Last-Event-ID header when reconnecting.

Signature:

func (o *SseEvent) WithId(id string) *SseEvent

Example:

result := instance.WithId("value")

Parameters:

Name Type Required Description
Id string Yes Unique identifier for this event

Returns: SseEvent

WithRetry()

Set the retry timeout for client reconnection

Sets the time in milliseconds clients should wait before attempting to reconnect if the connection is lost. The client browser will automatically handle reconnection.

Signature:

func (o *SseEvent) WithRetry(retryMs uint64) *SseEvent

Example:

result := instance.WithRetry(42)

Parameters:

Name Type Required Description
RetryMs uint64 Yes Retry timeout in milliseconds

Returns: SseEvent


StaticFilesConfig

Static file serving configuration

Field Type Default Description
Directory string — Directory path to serve
RoutePrefix string — URL path prefix (e.g., "/static")
IndexFile bool true Fallback to index.html for directories
CacheControl *string nil Cache-Control header value

TestingSseEvent

A single Server-Sent Event.

Field Type Default Description
Data string — The data field of the event.

UploadFile

Represents an uploaded file from multipart/form-data requests.

This struct provides efficient access to file content with automatic base64 decoding and implements standard I/O traits for compatibility.

Field Type Default Description
Filename string — Original filename from the client
ContentType *string nil MIME type of the uploaded file
Size *uint nil Size of the file in bytes
Content \[\]byte — File content (may be base64 encoded)
ContentEncoding *string nil Content encoding type
Methods
AsBytes()

Get the raw file content as bytes.

This provides zero-copy access to the underlying buffer.

Signature:

func (o *UploadFile) AsBytes() []byte

Example:

result := instance.AsBytes()

Returns: []byte

ReadToString()

Read the file content as a UTF-8 string.

Errors:

Returns an error if the content is not valid UTF-8.

Signature:

func (o *UploadFile) ReadToString() (string, error)

Example:

result, err := instance.ReadToString()
if err != nil {
    return err
}

Returns: string

Errors: Returns error.

ContentTypeOrDefault()

Get the content type, defaulting to "application/octet-stream".

Signature:

func (o *UploadFile) ContentTypeOrDefault() string

Example:

result := instance.ContentTypeOrDefault()

Returns: string


ValidateRequest

Request body for POST /asyncapi/validate

Field Type Default Description
Spec interface{} — Spec
Channel string — Channel
Message string — Message
Payload interface{} — Payload

ValidationResponse

Response body for POST /asyncapi/validate

Field Type Default Description
Valid bool — Valid
Errors \[\]string — Errors

Enums

Method

HTTP method

Value Description
Get Get
Post Post
Put Put
Patch Patch
Delete Delete
Head Head
Options Options
Connect Connect
Trace Trace

LifecycleHookPhase

The five lifecycle phases a hook can be registered against.

Used to resolve a per-route named hook selection (LifecycleHooksConfig in spikard-core.http) against the hooks actually registered on the server: a name is looked up within one specific phase's registered hooks, not across all five, so a hook registered for on_response can never be silently picked up by a route asking for on_request.

Value Description
OnRequest On request
PreValidation Pre validation
PreHandler Pre handler
OnResponse On response
OnError On error

SecuritySchemeInfo

Security scheme types

Value Description
Http Http — Fields: Scheme: string, BearerFormat: string
ApiKey Api key — Fields: Location: string, Name: string

Errors

AppError

Error type for application builder operations.

Variant Description
ErrRoute Route registration failed.
ErrServer Server/router construction failed.
ErrDecode Failed to extract DTO from the request context.
ErrGraphQL GraphQL route registration failed (e.g. an unrecognized schema_type).

GraphQlError

Errors that can occur during GraphQL operations

These errors are compatible with async-graphql error handling and can be converted to structured HTTP responses matching the project's error fixtures.

Variant Description
ErrExecutionError Error during schema execution Occurs when the GraphQL executor encounters a runtime error during query execution.
ErrSchemaBuildError Error during schema building Occurs when schema construction fails due to invalid definitions or conflicts.
ErrRequestHandlingError Error during request handling Occurs when the HTTP request cannot be properly handled or parsed.
ErrSerializationError Serialization error Occurs during JSON serialization/deserialization of GraphQL values.
ErrJsonError JSON parsing error Occurs when JSON input cannot be parsed.
ErrGraphQLValidationError GraphQL validation error Occurs when a GraphQL query fails schema validation.
ErrParseError GraphQL parse error Occurs when the GraphQL query string cannot be parsed.
ErrAuthenticationError Authentication error Occurs when request authentication fails.
ErrAuthorizationError Authorization error Occurs when user lacks required permissions.
ErrNotFound Not found error Occurs when a requested resource is not found.
ErrRateLimitExceeded Rate limit error Occurs when rate limit is exceeded.
ErrInvalidInput Invalid input error with validation details Occurs during input validation with detailed error information.
ErrGraphQLComplexityLimitExceeded Query complexity limit exceeded Occurs when a GraphQL query exceeds the configured complexity limit.
ErrGraphQLDepthLimitExceeded Query depth limit exceeded Occurs when a GraphQL query exceeds the configured depth limit.
ErrIntrospectionDisabled Introspection query rejected because introspection is disabled Occurs when a query selects __schema or __type while the schema was configured with introspection disabled.
ErrInternalError Internal server error Occurs when an unexpected internal error happens.

SchemaError

Error type for schema building operations

Variant Description
ErrBuildingFailed Generic schema building error
ErrSchemaValidationError Configuration validation error
ErrSchemaComplexityLimitExceeded Complexity limit exceeded
ErrSchemaDepthLimitExceeded Depth limit exceeded

Edit this page on GitHub