zoobzio December 15, 2025 Edit this page

API Reference

Complete reference for all rocco types and functions.

Constants

Host Constants

Constants for common host values used with Engine.Start().

ConstantValueDescription
HostAll""Bind to all interfaces (0.0.0.0)
HostLocal"localhost"Bind to loopback (localhost)
HostLoopback"127.0.0.1"Bind to loopback (127.0.0.1)
engine.Start(rocco.HostAll, 8080)      // All interfaces
engine.Start(rocco.HostLocal, 8080)    // Localhost only
engine.Start(rocco.HostLoopback, 8080) // 127.0.0.1 only

Engine

NewEngine

func NewEngine() *Engine

Creates a new Engine instance.

Engine Methods

WithAuthenticator

func (e *Engine) WithAuthenticator(extractor func(context.Context, *http.Request) (Identity, error)) *Engine

Sets the identity extraction function for authenticated handlers. Returns engine for chaining.

WithMiddleware

func (e *Engine) WithMiddleware(middleware ...func(http.Handler) http.Handler) *Engine

Adds global middleware. Returns engine for chaining.

WithHandlers

func (e *Engine) WithHandlers(handlers ...Endpoint) *Engine

Registers handlers with the engine. Returns engine for chaining.

WithSpec

func (e *Engine) WithSpec(spec *EngineSpec) *Engine

Sets the OpenAPI specification configuration.

WithOpenAPIInfo

func (e *Engine) WithOpenAPIInfo(info openapi.Info) *Engine

Sets OpenAPI Info metadata (title, version, description, etc.).

WithTag

func (e *Engine) WithTag(name, description string) *Engine

Adds or updates an OpenAPI tag with description.

WithTagGroup

func (e *Engine) WithTagGroup(name string, tags ...string) *Engine

Adds or updates a tag group for hierarchical tag organization. Rendered as the x-tagGroups vendor extension in the OpenAPI spec.

WithModels

func (e *Engine) WithModels(models ...*Model) *Engine

Registers standalone types into the OpenAPI component schemas. These types don't need to be handler input or output types — they are included in the spec for use by features like discriminated unions or external references. Returns engine for chaining.

WithCodec

func (e *Engine) WithCodec(codec Codec) *Engine

Sets the default codec for all handlers registered with this engine. Handlers that explicitly call WithCodec() will use their own codec instead.

WithTLSConfig

func (e *Engine) WithTLSConfig(config *tls.Config) *Engine

Sets the TLS configuration for the engine's HTTP server. When set, the server will use TLS (HTTPS) instead of plain HTTP. Certificates should be provided via the tls.Config (e.g., using tls.Config.Certificates or tls.Config.GetCertificate).

Router

func (e *Engine) Router() *http.ServeMux

Returns the underlying stdlib ServeMux for advanced use cases.

GenerateOpenAPI

func (e *Engine) GenerateOpenAPI(identity Identity) *openapi.OpenAPI

Generates OpenAPI specification. Pass an Identity to filter handlers by permissions, or nil for all handlers.

Start

func (e *Engine) Start(host string, port int) error

Starts the HTTP server on the given host and port. Blocks until shutdown.

ParameterTypeDescription
hoststringHost to bind to (empty string for all interfaces)
portintPort to listen on

Shutdown

func (e *Engine) Shutdown(ctx context.Context) error

Gracefully shuts down the server, waiting for active requests.

Handler

HTTP Method Shortcuts

The preferred way to create handlers:

func GET[In, Out any](path string, fn func(*Request[In]) (Out, error)) *Handler[In, Out]
func POST[In, Out any](path string, fn func(*Request[In]) (Out, error)) *Handler[In, Out]
func PUT[In, Out any](path string, fn func(*Request[In]) (Out, error)) *Handler[In, Out]
func PATCH[In, Out any](path string, fn func(*Request[In]) (Out, error)) *Handler[In, Out]
func DELETE[In, Out any](path string, fn func(*Request[In]) (Out, error)) *Handler[In, Out]
ParameterTypeDescription
pathstringURL path with optional parameters (e.g., "/users/{id}")
fnfunc(*Request[In]) (Out, error)Handler function

Handler names are auto-generated from method and path with a random suffix for uniqueness (e.g., GET /users/{id}get-users-id-a3f1b2c4).

NewHandler

func NewHandler[In, Out any](name string, method, path string, fn func(*Request[In]) (Out, error)) *Handler[In, Out]

Creates a new typed handler with explicit name. Use HTTP method shortcuts above for most cases.

ParameterTypeDescription
namestringHandler name for logging and OpenAPI operationId
methodstringHTTP method (GET, POST, PUT, PATCH, DELETE)
pathstringURL path with optional parameters (e.g., "/users/{id}")
fnfunc(*Request[In]) (Out, error)Handler function

Handler Methods

WithName

func (h *Handler[In, Out]) WithName(name string) *Handler[In, Out]

Sets a custom handler name, overriding the auto-generated one. Affects OpenAPI operationId and log entries.

WithSummary

func (h *Handler[In, Out]) WithSummary(summary string) *Handler[In, Out]

Sets OpenAPI summary (short description).

WithDescription

func (h *Handler[In, Out]) WithDescription(desc string) *Handler[In, Out]

Sets OpenAPI description (detailed, supports markdown).

WithTags

func (h *Handler[In, Out]) WithTags(tags ...string) *Handler[In, Out]

Sets OpenAPI tags for grouping operations.

WithSuccessStatus

func (h *Handler[In, Out]) WithSuccessStatus(status int) *Handler[In, Out]

Sets HTTP status code for successful responses. Default: 200.

WithPathParams

func (h *Handler[In, Out]) WithPathParams(params ...string) *Handler[In, Out]

Declares required path parameters.

WithQueryParams

func (h *Handler[In, Out]) WithQueryParams(params ...string) *Handler[In, Out]

Declares query parameters.

WithResponseHeaders

func (h *Handler[In, Out]) WithResponseHeaders(headers map[string]string) *Handler[In, Out]

Sets default response headers.

WithErrors

func (h *Handler[In, Out]) WithErrors(errs ...ErrorDefinition) *Handler[In, Out]

Declares errors this handler may return.

WithMaxBodySize

func (h *Handler[In, Out]) WithMaxBodySize(size int64) *Handler[In, Out]

Sets maximum request body size in bytes. Default: 10MB.

WithOutputValidation

func (h *Handler[In, Out]) WithOutputValidation() *Handler[In, Out]

Enables output validation. Disabled by default.

WithCodec

func (h *Handler[In, Out]) WithCodec(codec Codec) *Handler[In, Out]

Sets the codec for request/response serialization. Overrides engine default. Default: JSON.

WithMiddleware

func (h *Handler[In, Out]) WithMiddleware(middleware ...func(http.Handler) http.Handler) *Handler[In, Out]

Adds handler-specific middleware.

WithAuthentication

func (h *Handler[In, Out]) WithAuthentication() *Handler[In, Out]

Marks handler as requiring authentication.

WithScopes

func (h *Handler[In, Out]) WithScopes(scopes ...string) *Handler[In, Out]

Requires one of the specified scopes (OR logic). Multiple calls create AND logic.

WithRoles

func (h *Handler[In, Out]) WithRoles(roles ...string) *Handler[In, Out]

Requires one of the specified roles (OR logic). Multiple calls create AND logic.

WithUsageLimit

func (h *Handler[In, Out]) WithUsageLimit(key string, thresholdFunc func(Identity) int) *Handler[In, Out]

Adds usage limit check based on identity stats.

StreamHandler

NewStreamHandler

func NewStreamHandler[In, Out any](name string, method, path string, fn func(*Request[In], Stream[Out]) error) *StreamHandler[In, Out]

Creates a new typed streaming handler for Server-Sent Events.

ParameterTypeDescription
namestringHandler name for logging and documentation
methodstringHTTP method (typically GET or POST)
pathstringURL path with optional parameters
fnfunc(*Request[In], Stream[Out]) errorStream handler function

StreamHandler Methods

StreamHandler supports the same builder methods as Handler:

  • WithSummary(summary string) - Sets OpenAPI summary
  • WithDescription(desc string) - Sets OpenAPI description
  • WithTags(tags ...string) - Sets OpenAPI tags
  • WithPathParams(params ...string) - Declares path parameters
  • WithQueryParams(params ...string) - Declares query parameters
  • WithErrors(errs ...ErrorDefinition) - Declares possible errors
  • WithMiddleware(middleware ...func(http.Handler) http.Handler) - Adds middleware
  • WithAuthentication() - Requires authentication
  • WithScopes(scopes ...string) - Requires scopes
  • WithRoles(roles ...string) - Requires roles

Stream

type Stream[T any] interface {
    Send(data T) error
    SendEvent(event string, data T) error
    SendComment(comment string) error
    Done() <-chan struct{}
}

Interface for sending SSE events.

Send

func (s Stream[T]) Send(data T) error

Sends a data-only event. Data is JSON-encoded.

SendEvent

func (s Stream[T]) SendEvent(event string, data T) error

Sends a named event with data. Allows client-side event filtering.

SendComment

func (s Stream[T]) SendComment(comment string) error

Sends a comment (prefixed with :). Useful for keep-alive.

Done

func (s Stream[T]) Done() <-chan struct{}

Returns a channel closed when the client disconnects. Use in select statements to detect disconnection.

Request

type Request[In any] struct {
    context.Context // Embedded for deadline, cancellation, values
    *http.Request   // Embedded for direct access when needed
    Params          *Params
    Body            In
    Identity        Identity
}
FieldTypeDescription
context.ContextembeddedRequest context (deadline, cancellation, values)
*http.RequestembeddedUnderlying HTTP request (use sparingly)
Params*ParamsPath and query parameters
BodyInParsed and validated request body
IdentityIdentityAuthenticated identity (or NoIdentity)

Params

type Params struct {
    Path  map[string]string
    Query map[string]string
}
FieldTypeDescription
Pathmap[string]stringPath parameters (e.g., {id})
Querymap[string]stringQuery parameters

NoBody

type NoBody struct{}

Empty struct for handlers without request bodies.

Identity

type Identity interface {
    ID() string
    TenantID() string
    HasScope(scope string) bool
    HasRole(role string) bool
    Stats() map[string]int
}
MethodReturnDescription
ID()stringUnique identifier
TenantID()stringTenant/organization ID
HasScope(scope)boolCheck if identity has scope
HasRole(role)boolCheck if identity has role
Stats()map[string]intUsage statistics for rate limiting

NoIdentity

type NoIdentity struct{}

Default identity for unauthenticated requests. All methods return empty/false values.

EngineConfig

type EngineConfig struct {
    Host         string
    Port         int
    ReadTimeout  time.Duration
    WriteTimeout time.Duration
    IdleTimeout  time.Duration
}
FieldTypeDefaultDescription
Hoststring-Bind host
Portint-Listen port
ReadTimeouttime.Duration120sRead timeout
WriteTimeouttime.Duration120sWrite timeout
IdleTimeouttime.Duration120sIdle timeout

EngineSpec

type EngineSpec struct {
    Info      openapi.Info
    Tags      []openapi.Tag
    TagGroups []openapi.TagGroup
}

OpenAPI specification configuration.

HandlerSpec

type HandlerSpec struct {
    Name           string
    Method         string
    Path           string
    Summary        string
    Description    string
    Tags           []string
    PathParams     []string
    QueryParams    []string
    InputTypeName  string
    OutputTypeName string
    SuccessStatus  int
    ErrorCodes     []int
    ContentType    string
    RequiresAuth   bool
    ScopeGroups    [][]string
    RoleGroups     [][]string
    UsageLimits    []UsageLimit
}

Handler metadata for OpenAPI generation.

UsageLimit

type UsageLimit struct {
    Key           string
    ThresholdFunc func(Identity) int
}

Usage limit configuration for rate limiting.

Model

NewModel

func NewModel[T any]() *Model

Scans T with sentinel and returns a Model for OpenAPI schema registration. Use with Engine.WithModels() to include types in the spec that aren't handler input or output types.

engine.WithModels(
    rocco.NewModel[IngestCompletedEvent](),
    rocco.NewModel[IngestFailedEvent](),
)

Codec

type Codec interface {
    ContentType() string
    Marshal(v any) ([]byte, error)
    Unmarshal(data []byte, v any) error
}

Interface for request/response serialization.

MethodReturnDescription
ContentType()stringMIME type (e.g., "application/json")
Marshal(v)([]byte, error)Encodes value to bytes
Unmarshal(data, v)errorDecodes bytes into value

JSONCodec

type JSONCodec struct{}

Default codec implementation using encoding/json.

Validatable

type Validatable interface {
    Validate() error
}

Interface for types that can validate themselves. Input and output types implement this interface to opt-in to automatic validation.

NewValidationError

func NewValidationError(fields []ValidationFieldError) error

Creates a validation error with field-level details. Use this in your Validate() implementations to return structured validation errors that rocco can format correctly.

Example

import "github.com/zoobz-io/check"

type CreateUserInput struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func (c CreateUserInput) Validate() error {
    return check.All(
        check.Required(c.Name, "name"),
        check.Email(c.Email, "email"),
    )
}

Endpoint

type Endpoint interface {
    Process(ctx context.Context, r *http.Request, w http.ResponseWriter) (int, error)
    Spec() HandlerSpec
    ErrorDefs() []ErrorDefinition
    Middleware() []func(http.Handler) http.Handler
    Close() error
}

Interface implemented by Handler.

MethodDescription
Process(...)Handles the HTTP request and writes the response
Spec()Returns the declarative specification for this handler
ErrorDefs()Returns declared error definitions for OpenAPI generation
Middleware()Returns handler-specific middleware
Close()Lifecycle cleanup

See Also