arc

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: MIT Imports: 36 Imported by: 0

README

arc

arc is a typed HTTP/API runtime core for Go.

It provides:

  • a custom router
  • typed handlers
  • request binding and validation
  • error mapping
  • response encoding
  • OpenAPI 3.1 + JSON Schema generation
  • middleware and observability hooks
  • built-in Swagger UI docs

Scope

This README is the canonical scope/status document for the repository.

Implemented:

  • custom router (path params, catch-all, groups, HEAD/OPTIONS)
  • typed handlers (Response, raw, stream, SSE, websocket helper)
  • binding from path/query/header/cookie/body/form/multipart (including multipart files)
  • validation (required, min/max, min/max length, regex, enum, format, cross-field, custom validators)
  • OpenAPI 3.1 and JSON Schema generation
  • content negotiation (application/json, application/problem+json, vendor +json matching)
  • middleware pipeline and observability hooks
  • tenant extraction (header/path/cookie/JWT)
  • query DTO + include parsing + include tree helpers
  • API versioning middleware and route version markers
  • response caching with ETag/304 and invalidation middleware
  • OpenAPI callbacks support
  • server lifecycle (/health, /ready, graceful shutdown)

arc currently integrates with orm directly (arc -> orm).

The adapter abstraction layer is not implemented yet by design in the current scope. This is a known and intentional limitation for the current version.

Quick Start

e := arc.New()

type In struct {
    ID int64 `path:"id" validate:"required,min=1"`
}
type Out struct {
    ID int64 `json:"id"`
}

arc.Handle(e, "GET", "/users/{id}", "users_get", func(ctx context.Context, in *In) (*arc.Response[Out], error) {
    return arc.OK(Out{ID: in.ID}), nil
})

e.RegisterSystemRoutes("/openapi.json", "/docs")

CLI: OpenAPI Generator

cmd/arc generates OpenAPI from registered routes.

Example:

go run ./cmd/arc -format json -out openapi.json
go run ./cmd/arc -format yaml -out openapi.yaml
go run ./cmd/arc -format json -stdout
go run ./cmd/arc -format json -out openapi.json -validate-quality

Flags:

  • -out output file path (default: openapi.json)
  • -format json|yaml (default: json)
  • -stdout print spec to stdout instead of writing file
  • -with-system include system routes (/openapi.json, /openapi.yaml, /docs, /schemas)
  • -validate-quality enforce OpenAPI quality gates and fail with exit code 2 on violations
  • -require-tags require root tags list (default: true)
  • -require-servers require root servers list (default: true)
  • -require-security-schemes comma-separated required components.securitySchemes names (default: BearerAuth)
  • -require-examples require at least one operation-level request/response example (default: false)

CI usage example:

go run ./cmd/arc -format json -out openapi/openapi.json \
  -validate-quality \
  -require-tags \
  -require-servers \
  -require-security-schemes BearerAuth

To plug your own route registrations for generation, add a file in cmd/arc and assign RegisterRoutes in init():

func init() {
    RegisterRoutes = func(e *arc.Engine) {
        // register routes here
    }
}

Built-in Endpoints

  • /openapi.json
  • /openapi.yaml
  • /docs (Swagger UI)
  • /schemas
  • /schemas/{name}
  • /health
  • /ready

CI/CD

GitHub Actions workflows:

  • CI (.github/workflows/ci.yml): go vet, go test, and go build ./cmd/arc on push/PR.
  • Release (.github/workflows/release.yml): builds cmd/arc binaries for Linux/macOS/Windows on v* tags and publishes assets to GitHub Releases.

Development

Run tests:

go test ./...

License

MIT. See LICENSE.md.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var EnableLegacyTagSync = true

EnableLegacyTagSync controls one-time migration of legacy struct tags into typemeta.Attributes. Keeping it enabled preserves backward compatibility while bind/validate rely on typemeta only.

Functions

func APIVersionFromContext

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

APIVersionFromContext returns resolved API version.

func CacheControlHeaders

func CacheControlHeaders(maxAge time.Duration) http.Header

CacheControlHeaders helper for response cache directives.

func ConfigureFieldMetadata

func ConfigureFieldMetadata(model any, fieldGoName string, cfg FieldMetadataConfig) error

ConfigureFieldMetadata writes arc binding/validation metadata into orm.SharedTypeRegistry attributes.

func DefaultDocsHTML

func DefaultDocsHTML(openapiPath string) string

DefaultDocsHTML returns API docs page backed by Swagger UI CDN.

func FlattenIncludeTree

func FlattenIncludeTree(tree IncludeTree) []string

FlattenIncludeTree returns sorted flat include list from tree.

func Handle

func Handle[Input any, Output any](e *Engine, method, path, operationID string, h func(context.Context, *Input) (*Response[Output], error), opts ...RouteOption)

Handle registers typed handler of shape func(ctx, *Input) (*Response[Output], error).

func HandleErr

func HandleErr[Input any](e *Engine, method, path, operationID string, h func(context.Context, *Input) error, opts ...RouteOption)

HandleErr registers handler of shape func(ctx, *Input) error.

func HandleGroup

func HandleGroup[Input any, Output any](g *Group, method, path, operationID string, h func(context.Context, *Input) (*Response[Output], error), opts ...RouteOption)

Handle registers typed handler in group.

func HandleOut

func HandleOut[Input any, Output any](e *Engine, method, path, operationID string, h func(context.Context, *Input) (*Output, error), opts ...RouteOption)

HandleOut registers handler of shape func(ctx, *Input) (*Output, error).

func HandleRawTyped

func HandleRawTyped[Input any](e *Engine, method, path, operationID string, h func(context.Context, *Input) (*RawResponse, error), opts ...RouteOption)

HandleRawTyped registers handler of shape func(ctx, *Input) (*RawResponse, error).

func HandleSSE

func HandleSSE[Input any](e *Engine, method, path, operationID string, h func(context.Context, *Input, *SSEWriter) error, opts ...RouteOption)

HandleSSE registers route that streams server-sent events.

func HandleStreamTyped

func HandleStreamTyped[Input any](e *Engine, method, path, operationID string, h func(context.Context, *Input) (*StreamResponse, error), opts ...RouteOption)

HandleStreamTyped registers handler of shape func(ctx, *Input) (*StreamResponse, error).

func HandleWebSocket

func HandleWebSocket[Input any](e *Engine, method, path, operationID string, cfg WSConfig, h func(context.Context, *Input, *WSConn) error, opts ...RouteOption)

HandleWebSocket registers websocket endpoint helper.

func HasInclude

func HasInclude(ctx context.Context, path string) bool

HasInclude reports whether exact include path was requested.

func IncludesFromContext

func IncludesFromContext(ctx context.Context) []string

IncludesFromContext returns validated include paths.

func ParseIncludes

func ParseIncludes(raw string, allowlist []string) ([]string, error)

ParseIncludes parses comma-separated include and validates against allowlist.

func RegisterValidator

func RegisterValidator[T any](e *Engine, fn func(*T) error)

RegisterValidator registers additional struct validator for input type T.

func TenantFromContext

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

TenantFromContext returns tenant value.

func ValidateOpenAPIQuality added in v0.1.1

func ValidateOpenAPIQuality(spec map[string]any, gates OpenAPIQualityGates) []string

ValidateOpenAPIQuality checks generated spec against requested quality gates. It returns a list of violations; empty result means the spec passed.

func WithAPIVersion

func WithAPIVersion(ctx context.Context, version string) context.Context

WithAPIVersion stores resolved API version in context.

func WithIncludes

func WithIncludes(ctx context.Context, includes []string) context.Context

WithIncludes stores validated include paths in context.

func WithListQueryDTO

func WithListQueryDTO(ctx context.Context, dto ListQueryDTO) context.Context

WithListQueryDTO stores parsed list query DTO in context.

Types

type APIError

type APIError struct {
	Status    int           `json:"-"`
	Code      string        `json:"code"`
	Message   string        `json:"message"`
	Details   []ErrorDetail `json:"details,omitempty"`
	RequestID string        `json:"requestId,omitempty"`
}

APIError is standard error payload.

func BadRequest

func BadRequest(code, message string) *APIError

BadRequest creates 400 API error.

func Validation

func Validation(code, message string) *APIError

Validation creates 422 API error.

func (*APIError) Error

func (e *APIError) Error() string

type APIVersionSource

type APIVersionSource string

APIVersionSource identifies request source for API version extraction.

const (
	APIVersionSourceHeader APIVersionSource = "header"
	APIVersionSourceQuery  APIVersionSource = "query"
	APIVersionSourceAccept APIVersionSource = "accept"
)

type APIVersioningConfig

type APIVersioningConfig struct {
	Header         string
	QueryParam     string
	AcceptParam    string
	Sources        []APIVersionSource
	DefaultVersion string
	Required       bool
	ResponseHeader string
}

APIVersioningConfig configures API version extraction middleware.

type CacheConfig

type CacheConfig struct {
	TTL            time.Duration
	VaryHeaders    []string
	SkipAuthorized bool
	SkipCookies    bool
	Store          *ResponseCache
}

CacheConfig configures in-memory response cache middleware.

type CacheInvalidationConfig

type CacheInvalidationConfig struct {
	Store                 *ResponseCache
	Methods               []string
	PathPrefixes          []string
	PathPrefixResolver    func(*http.Request) []string
	ClearOnAnyMatch       bool
	InvalidateRequestPath bool
}

CacheInvalidationConfig configures cache invalidation middleware.

type Encoder

type Encoder interface {
	Encode(w http.ResponseWriter, status int, body any) error
}

Encoder writes response payload.

type Engine

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

Engine is HTTP/API runtime core.

func New

func New() *Engine

New creates arc engine with defaults.

func (*Engine) AddObserver

func (e *Engine) AddObserver(obs Observer)

AddObserver adds request observer hooks.

func (*Engine) AddOpenAPIServer added in v0.1.1

func (e *Engine) AddOpenAPIServer(url, description string)

AddOpenAPIServer appends one server entry with URL and optional description.

func (*Engine) Group

func (e *Engine) Group(prefix string, middleware ...Middleware) *Group

Group creates route group.

func (*Engine) IsReady

func (e *Engine) IsReady() bool

IsReady reports current readiness state.

func (*Engine) MarshalOpenAPIJSON

func (e *Engine) MarshalOpenAPIJSON() ([]byte, error)

MarshalOpenAPIJSON renders current OpenAPI spec as JSON bytes.

func (*Engine) MarshalOpenAPIYAML

func (e *Engine) MarshalOpenAPIYAML() ([]byte, error)

MarshalOpenAPIYAML renders current OpenAPI spec as YAML bytes.

func (*Engine) OpenAPISpec added in v0.1.1

func (e *Engine) OpenAPISpec() map[string]any

OpenAPISpec returns current OpenAPI spec as map.

func (*Engine) Operations

func (e *Engine) Operations() []Operation

Operations returns copy of registered operations.

func (*Engine) RegisterEncoder

func (e *Engine) RegisterEncoder(contentType string, enc Encoder)

RegisterEncoder registers encoder for specific media type.

func (*Engine) RegisterHealthRoutes

func (e *Engine) RegisterHealthRoutes()

func (*Engine) RegisterOpenAPISecurityScheme added in v0.1.1

func (e *Engine) RegisterOpenAPISecurityScheme(name string, scheme map[string]any)

RegisterOpenAPISecurityScheme registers components.securitySchemes entry.

func (*Engine) RegisterRaw

func (e *Engine) RegisterRaw(method, path, operationID string, h Handler, middleware ...Middleware)

RegisterRaw registers raw route handler.

func (*Engine) RegisterSchemaRoutes

func (e *Engine) RegisterSchemaRoutes(listPath, itemPath string)

RegisterSchemaRoutes mounts JSON Schema endpoints.

func (*Engine) RegisterSystemRoutes

func (e *Engine) RegisterSystemRoutes(openapiPath, docsPath string)

RegisterSystemRoutes mounts openapi and docs endpoints.

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

func (*Engine) SetEncoder

func (e *Engine) SetEncoder(enc Encoder)

SetEncoder overrides response encoder.

func (*Engine) SetErrorMapper

func (e *Engine) SetErrorMapper(m ErrorMapper)

SetErrorMapper overrides default mapper.

func (*Engine) SetOpenAPIServers added in v0.1.1

func (e *Engine) SetOpenAPIServers(servers []map[string]any)

SetOpenAPIServers configures root OpenAPI servers list.

func (*Engine) SetReady

func (e *Engine) SetReady(v bool)

SetReady updates engine readiness state.

func (*Engine) Use

func (e *Engine) Use(mw ...Middleware)

Use adds global middleware.

func (*Engine) Version

func (e *Engine) Version(version string, middleware ...Middleware) *Group

Version creates versioned group with /v<version> prefix and version marker.

type ErrorDetail

type ErrorDetail struct {
	Path    string `json:"path,omitempty"`
	Code    string `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
}

ErrorDetail describes one validation/binding problem.

type ErrorMapper

type ErrorMapper interface {
	MapError(err error) *APIError
}

ErrorMapper converts domain/runtime errors into API error payload.

type FieldMetadataConfig

type FieldMetadataConfig struct {
	Path     string
	Query    string
	Header   string
	Cookie   string
	Form     string
	Validate string
}

FieldMetadataConfig configures arc-specific metadata for one field in shared typemeta.

type Group

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

Group holds shared route config.

func (*Group) Group

func (g *Group) Group(prefix string, middleware ...Middleware) *Group

Group creates nested group.

func (*Group) WithAcceptVersioning

func (g *Group) WithAcceptVersioning(param string, required bool, defaultVersion string) *Group

WithAcceptVersioning resolves API version only from Accept parameter within this group.

func (*Group) WithCallbacks

func (g *Group) WithCallbacks(callbacks map[string]any) *Group

WithCallbacks returns group copy with inherited OpenAPI callbacks.

func (*Group) WithHeaderVersioning

func (g *Group) WithHeaderVersioning(header string, required bool, defaultVersion string) *Group

WithHeaderVersioning resolves API version only from header within this group.

func (*Group) WithIncludeAllowlist

func (g *Group) WithIncludeAllowlist(paths ...string) *Group

WithIncludeAllowlist returns group copy with inherited include allowlist.

func (*Group) WithIncludeParamName

func (g *Group) WithIncludeParamName(name string) *Group

WithIncludeParamName returns group copy with inherited include query name.

func (*Group) WithMetadata

func (g *Group) WithMetadata(items map[string]string) *Group

WithMetadata returns group copy with inherited operation metadata.

func (*Group) WithQueryDTO

func (g *Group) WithQueryDTO() *Group

WithQueryDTO returns group copy that enables query DTO parsing.

func (*Group) WithQueryVersioning

func (g *Group) WithQueryVersioning(param string, required bool, defaultVersion string) *Group

WithQueryVersioning resolves API version only from query param within this group.

func (*Group) WithSecurity

func (g *Group) WithSecurity(items ...string) *Group

WithSecurity returns group copy with inherited security schemes.

func (*Group) WithTags

func (g *Group) WithTags(tags ...string) *Group

WithTags returns group copy with inherited tags.

func (*Group) WithVersion

func (g *Group) WithVersion(version string) *Group

WithVersion returns group copy with inherited API version marker.

func (*Group) WithVersioning

func (g *Group) WithVersioning(cfg APIVersioningConfig) *Group

WithVersioning returns group copy with API version extraction middleware.

type HMACJWTVerifier

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

HMACJWTVerifier verifies JWT with HMAC SHA algorithms.

func NewHMACJWTVerifier

func NewHMACJWTVerifier(secret []byte, allowedAlgs ...string) *HMACJWTVerifier

NewHMACJWTVerifier creates HMAC JWT verifier for HS256/HS384/HS512.

func (*HMACJWTVerifier) VerifyAndParse

func (v *HMACJWTVerifier) VerifyAndParse(token string) (map[string]any, error)

VerifyAndParse verifies JWT signature and temporal claims.

func (*HMACJWTVerifier) WithLeeway

func (v *HMACJWTVerifier) WithLeeway(d time.Duration) *HMACJWTVerifier

WithLeeway configures allowed clock skew for exp/nbf/iat checks.

type Handler

type Handler func(*RequestContext) error

Handler executes one route operation.

type IncludeTree

type IncludeTree map[string]IncludeTree

IncludeTree represents nested include graph: profile, roles.permissions, ...

func BuildIncludeTree

func BuildIncludeTree(includes []string) IncludeTree

BuildIncludeTree builds nested relation tree from flat include paths.

func IncludeTreeFromContext

func IncludeTreeFromContext(ctx context.Context) IncludeTree

IncludeTreeFromContext returns nested relation tree from includes in context.

type JSONEncoder

type JSONEncoder struct{}

JSONEncoder writes JSON payloads.

func (JSONEncoder) Encode

func (JSONEncoder) Encode(w http.ResponseWriter, status int, body any) error

type JWTVerifier

type JWTVerifier interface {
	VerifyAndParse(token string) (map[string]any, error)
}

JWTVerifier verifies JWT signature and temporal claims.

type ListQueryDTO

type ListQueryDTO struct {
	Limit   *int                `json:"limit,omitempty"`
	Offset  *int                `json:"offset,omitempty"`
	Sort    []SortField         `json:"sort,omitempty"`
	Include []string            `json:"include,omitempty"`
	Filters map[string][]string `json:"filters,omitempty"`
}

ListQueryDTO contains normalized list-query primitives.

func QueryDTOFromContext

func QueryDTOFromContext(ctx context.Context) (ListQueryDTO, bool)

QueryDTOFromContext returns parsed list query DTO.

type Middleware

type Middleware func(Handler) Handler

Middleware wraps route handler.

func APIVersioning

func APIVersioning(cfg APIVersioningConfig) Middleware

APIVersioning resolves API version from request metadata and injects it into context.

func CacheResponses

func CacheResponses(ttl time.Duration) Middleware

CacheResponses caches GET/HEAD responses in-memory for ttl.

func CacheResponsesWithConfig

func CacheResponsesWithConfig(cfg CacheConfig) Middleware

CacheResponsesWithConfig caches responses using explicit cache configuration.

func InvalidateCacheOnWrite

func InvalidateCacheOnWrite(cfg CacheInvalidationConfig) Middleware

InvalidateCacheOnWrite clears/invalidate cache entries after mutating requests.

func Logger

func Logger(logger *log.Logger) Middleware

Logger logs request latency and status.

func Recovery

func Recovery() Middleware

Recovery converts panic into API error.

func TenantExtractor

func TenantExtractor(extractors ...TenantResolveFunc) Middleware

TenantExtractor reads tenant from request and injects into context.

type Observer

type Observer interface {
	OnRequestStart(*RequestContext)
	OnRequestEnd(*RequestContext, int, error, time.Duration)
}

Observer receives request lifecycle events for logging/metrics/tracing.

type ObserverFunc

type ObserverFunc struct {
	Start func(*RequestContext)
	End   func(*RequestContext, int, error, time.Duration)
}

ObserverFunc allows plugging simple callbacks.

func (ObserverFunc) OnRequestEnd

func (o ObserverFunc) OnRequestEnd(rc *RequestContext, status int, err error, d time.Duration)

func (ObserverFunc) OnRequestStart

func (o ObserverFunc) OnRequestStart(rc *RequestContext)

type OpenAPIQualityGates added in v0.1.1

type OpenAPIQualityGates struct {
	RequireRootTags         bool
	RequireServers          bool
	RequireExamples         bool
	RequiredSecuritySchemes []string
}

OpenAPIQualityGates configures required quality constraints for generated OpenAPI.

type Operation

type Operation struct {
	Method           string
	Path             string
	OperationID      string
	Handler          Handler
	Middleware       []Middleware
	Metadata         map[string]string
	Version          string
	Callbacks        map[string]any
	InputType        any
	OutputType       any
	Tags             []string
	Security         []string
	MiddlewareN      int
	Params           []OperationParam
	HasRequestBody   bool
	HasFormBody      bool
	InputContentType string
	ResponseKind     responseKind
	IncludeAllowlist []string
	IncludeParamName string
	HasQueryDTO      bool
	RequestExamples  map[string]any
	ResponseExamples map[string]any
	ProblemStatuses  []int
	ProblemExamples  map[int]map[string]any
}

Operation describes registered endpoint.

type OperationParam

type OperationParam struct {
	Name     string
	In       string
	Required bool
	Schema   map[string]any
}

OperationParam describes one OpenAPI operation parameter.

type OperationRegistry

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

OperationRegistry stores all operations.

func NewOperationRegistry

func NewOperationRegistry() *OperationRegistry

func (*OperationRegistry) Add

func (r *OperationRegistry) Add(op Operation)

func (*OperationRegistry) JSONSchemaForType

func (r *OperationRegistry) JSONSchemaForType(model any) map[string]any

JSONSchemaForType generates JSON Schema for one Go type.

func (*OperationRegistry) JSONSchemas

func (r *OperationRegistry) JSONSchemas() map[string]any

JSONSchemas returns generated component schemas from registered operations.

func (*OperationRegistry) List

func (r *OperationRegistry) List() []Operation

func (*OperationRegistry) MarshalJSONSchemasJSON

func (r *OperationRegistry) MarshalJSONSchemasJSON() ([]byte, error)

MarshalJSONSchemasJSON renders all generated schemas as JSON bytes.

func (*OperationRegistry) MarshalOpenAPIJSON

func (r *OperationRegistry) MarshalOpenAPIJSON() ([]byte, error)

MarshalOpenAPIJSON renders OpenAPI spec as JSON bytes.

func (*OperationRegistry) MarshalOpenAPIYAML

func (r *OperationRegistry) MarshalOpenAPIYAML() ([]byte, error)

MarshalOpenAPIYAML renders OpenAPI spec as YAML bytes.

func (*OperationRegistry) OpenAPISpec

func (r *OperationRegistry) OpenAPISpec() map[string]any

func (*OperationRegistry) RegisterSecurityScheme added in v0.1.1

func (r *OperationRegistry) RegisterSecurityScheme(name string, scheme map[string]any)

RegisterSecurityScheme registers OpenAPI security scheme in components.

func (*OperationRegistry) SetServers added in v0.1.1

func (r *OperationRegistry) SetServers(servers []map[string]any)

SetServers configures root OpenAPI servers list.

func (*OperationRegistry) Update

func (r *OperationRegistry) Update(method, path, operationID string, fn func(*Operation))

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional stores tri-state field state for PATCH DTOs: absent, explicit null, explicit value.

func Null

func Null[T any]() Optional[T]

Null creates optional with explicit null.

func Some

func Some[T any](v T) Optional[T]

Some creates optional with explicit value.

func (Optional[T]) IsNull

func (o Optional[T]) IsNull() bool

IsNull reports whether field was explicitly set to null.

func (Optional[T]) IsSet

func (o Optional[T]) IsSet() bool

IsSet reports whether field was provided.

func (Optional[T]) IsZero

func (o Optional[T]) IsZero() bool

IsZero makes omitempty work for absent state.

func (Optional[T]) MarshalJSON

func (o Optional[T]) MarshalJSON() ([]byte, error)

MarshalJSON encodes absent/null as null and explicit value as JSON value.

func (Optional[T]) OptionalIsNull

func (o Optional[T]) OptionalIsNull() bool

OptionalIsNull exposes null state for validation internals.

func (Optional[T]) OptionalIsSet

func (o Optional[T]) OptionalIsSet() bool

OptionalIsSet exposes set state for validation internals.

func (Optional[T]) OptionalValueAny

func (o Optional[T]) OptionalValueAny() any

OptionalValueAny returns underlying value for validation internals.

func (*Optional[T]) Set

func (o *Optional[T]) Set(v T)

Set marks value as explicitly set.

func (*Optional[T]) SetNull

func (o *Optional[T]) SetNull()

SetNull marks value as explicit null.

func (*Optional[T]) UnmarshalJSON

func (o *Optional[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON tracks absent/null/value state.

func (*Optional[T]) UnmarshalText

func (o *Optional[T]) UnmarshalText(text []byte) error

UnmarshalText supports binding from query/header/cookie/form.

func (*Optional[T]) Unset

func (o *Optional[T]) Unset()

Unset marks value as absent.

func (Optional[T]) Value

func (o Optional[T]) Value() (T, bool)

Value returns value when set and non-null.

type OptionalBool

type OptionalBool = Optional[bool]

OptionalBool is convenience alias for Optional[bool].

type OptionalInt

type OptionalInt = Optional[int]

OptionalInt is convenience alias for Optional[int].

type OptionalString

type OptionalString = Optional[string]

OptionalString is convenience alias for Optional[string].

type ProblemExampleSpec added in v0.1.1

type ProblemExampleSpec struct {
	Code   string
	Detail string
}

ProblemExampleSpec describes one problem+json response example.

type RawResponse

type RawResponse struct {
	Status  int
	Headers http.Header
	WriteTo func(http.ResponseWriter) error
}

RawResponse allows writing arbitrary response formats.

func File

func File(status int, filename string, content []byte) *RawResponse

File returns raw file download response.

func Raw

func Raw(status int, contentType string, body []byte) *RawResponse

Raw creates raw response helper.

type RequestContext

type RequestContext struct {
	Writer  http.ResponseWriter
	Request *http.Request
	Params  map[string]string
	Engine  *Engine
	Ctx     context.Context
}

RequestContext carries request-scoped values.

type Response

type Response[T any] struct {
	Status  int
	Headers http.Header
	Body    *T
}

Response is typed HTTP response envelope.

func Created

func Created[T any](body T) *Response[T]

Created returns 201 response.

func JSON

func JSON[T any](status int, body T) *Response[T]

JSON returns custom status JSON response.

func NoContent

func NoContent() *Response[struct{}]

NoContent returns 204 response.

func OK

func OK[T any](body T) *Response[T]

OK returns 200 response.

type ResponseCache

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

ResponseCache stores cached HTTP responses.

func NewResponseCache

func NewResponseCache() *ResponseCache

NewResponseCache creates empty cache store.

func (*ResponseCache) Clear

func (c *ResponseCache) Clear()

Clear removes all cached entries.

func (*ResponseCache) InvalidatePathPrefix

func (c *ResponseCache) InvalidatePathPrefix(prefix string)

InvalidatePathPrefix removes cached entries where request path starts with prefix.

type Route

type Route struct {
	Handler    Handler
	Middleware []Middleware
}

Route describes runtime route entry.

type RouteOption

type RouteOption func(*routeConfig)

RouteOption configures operation metadata.

func WithCallbacks

func WithCallbacks(callbacks map[string]any) RouteOption

WithCallbacks attaches OpenAPI callbacks object for the route.

func WithIncludeAllowlist

func WithIncludeAllowlist(paths ...string) RouteOption

WithIncludeAllowlist enables relation include parsing and validation.

func WithIncludeParamName

func WithIncludeParamName(name string) RouteOption

WithIncludeParamName overrides include query parameter name (default: include).

func WithMetadata

func WithMetadata(items map[string]string) RouteOption

WithMetadata attaches operation metadata.

func WithMiddleware

func WithMiddleware(mw ...Middleware) RouteOption

WithMiddleware attaches route middleware.

func WithProblemResponseSpec added in v0.1.1

func WithProblemResponseSpec(spec map[int]ProblemExampleSpec) RouteOption

WithProblemResponseSpec registers explicit problem+json responses with examples.

func WithProblemResponses added in v0.1.1

func WithProblemResponses(statuses ...int) RouteOption

WithProblemResponses registers explicit problem+json responses for status codes.

func WithQueryDTO

func WithQueryDTO() RouteOption

WithQueryDTO enables parsing list query DTO from URL params.

func WithRequestExamples added in v0.1.1

func WithRequestExamples(examples map[string]any) RouteOption

WithRequestExamples attaches OpenAPI request body examples for operation input content type.

func WithResponseExamples added in v0.1.1

func WithResponseExamples(examples map[string]any) RouteOption

WithResponseExamples attaches OpenAPI 200 application/json examples.

func WithSecurity

func WithSecurity(items ...string) RouteOption

WithSecurity marks security schemes.

func WithTags

func WithTags(tags ...string) RouteOption

WithTags attaches OpenAPI tags.

func WithVersion

func WithVersion(version string) RouteOption

WithVersion marks API version for route metadata/OpenAPI extension.

type Router

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

Router is radix-like route tree per method.

func NewRouter

func NewRouter() *Router

NewRouter creates empty router.

func (*Router) Add

func (r *Router) Add(method, path string, route Route)

Add registers method/path.

func (*Router) AllowedMethods

func (r *Router) AllowedMethods(path string) []string

AllowedMethods returns methods matching the same path pattern.

func (*Router) Match

func (r *Router) Match(method, path string) (Route, map[string]string, bool)

Match resolves method/path.

type SSEEvent

type SSEEvent struct {
	ID    string
	Event string
	Data  string
	Retry time.Duration
}

SSEEvent describes one server-sent event.

type SSEWriter

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

SSEWriter writes SSE events to response stream.

func NewSSEWriter

func NewSSEWriter(w http.ResponseWriter) (*SSEWriter, error)

NewSSEWriter prepares SSE response headers.

func (*SSEWriter) WriteEvent

func (s *SSEWriter) WriteEvent(ev SSEEvent) error

WriteEvent sends one SSE frame.

type Server

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

Server wraps http.Server lifecycle helpers.

func NewServer

func NewServer(addr string, engine *Engine) *Server

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

func (*Server) Start

func (s *Server) Start() error

type SortField

type SortField struct {
	Field string `json:"field"`
	Desc  bool   `json:"desc"`
}

SortField describes one sorting clause.

type StreamResponse

type StreamResponse struct {
	Status      int
	ContentType string
	Reader      io.Reader
}

StreamResponse describes streaming body response.

func Stream

func Stream(status int, contentType string, reader io.Reader) *StreamResponse

Stream creates stream response helper.

type StructValidatorFunc

type StructValidatorFunc func(any) error

StructValidatorFunc validates one input struct instance.

type TenantResolveFunc

type TenantResolveFunc func(*RequestContext) (string, bool)

TenantResolveFunc extracts tenant id from request context.

func TenantFromCookie

func TenantFromCookie(name string) TenantResolveFunc

func TenantFromHeader

func TenantFromHeader(name string) TenantResolveFunc

func TenantFromJWTClaim

func TenantFromJWTClaim(claim string) TenantResolveFunc

TenantFromJWTClaim extracts tenant from Bearer JWT payload claim. It only decodes JWT payload and does not verify signature.

func TenantFromPath

func TenantFromPath(param string) TenantResolveFunc

func TenantFromVerifiedJWTClaim

func TenantFromVerifiedJWTClaim(claim string, verifier JWTVerifier) TenantResolveFunc

TenantFromVerifiedJWTClaim extracts tenant from verified JWT claim.

type ValidationErrors

type ValidationErrors struct {
	Details []ErrorDetail
}

ValidationErrors collects multiple input violations.

func (*ValidationErrors) Error

func (e *ValidationErrors) Error() string

type WSConfig

type WSConfig struct {
	CheckOrigin func(*http.Request) bool
}

WSConfig configures websocket upgrader behavior.

type WSConn

type WSConn struct {
	Conn *websocket.Conn
}

WSConn wraps websocket connection.

func (*WSConn) Close

func (c *WSConn) Close() error

Close closes websocket connection.

func (*WSConn) ReadText

func (c *WSConn) ReadText() (string, error)

ReadText reads text message.

func (*WSConn) WriteText

func (c *WSConn) WriteText(msg string) error

WriteText writes text message.

Jump to

Keyboard shortcuts

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