| title | API Reference | ||
|---|---|---|---|
| description | Complete API documentation for rocco | ||
| author | zoobzio | ||
| published | 2025-12-16 | ||
| updated | 2025-12-16 | ||
| tags |
|
Complete reference for all rocco types and functions.
Constants for common host values used with Engine.Start().
| Constant | Value | Description |
|---|---|---|
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 onlyfunc NewEngine() *EngineCreates a new Engine instance.
func (e *Engine) WithAuthenticator(extractor func(context.Context, *http.Request) (Identity, error)) *EngineSets the identity extraction function for authenticated handlers. Returns engine for chaining.
func (e *Engine) WithMiddleware(middleware ...func(http.Handler) http.Handler) *EngineAdds global middleware. Returns engine for chaining.
func (e *Engine) WithHandlers(handlers ...Endpoint) *EngineRegisters handlers with the engine. Returns engine for chaining.
func (e *Engine) WithSpec(spec *EngineSpec) *EngineSets the OpenAPI specification configuration.
func (e *Engine) WithOpenAPIInfo(info openapi.Info) *EngineSets OpenAPI Info metadata (title, version, description, etc.).
func (e *Engine) WithTag(name, description string) *EngineAdds or updates an OpenAPI tag with description.
func (e *Engine) WithTagGroup(name string, tags ...string) *EngineAdds or updates a tag group for hierarchical tag organization. Rendered as the x-tagGroups vendor extension in the OpenAPI spec.
func (e *Engine) WithModels(models ...*Model) *EngineRegisters 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.
func (e *Engine) WithCodec(codec Codec) *EngineSets the default codec for all handlers registered with this engine. Handlers that explicitly call WithCodec() will use their own codec instead.
func (e *Engine) WithTLSConfig(config *tls.Config) *EngineSets 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).
func (e *Engine) Router() *http.ServeMuxReturns the underlying stdlib ServeMux for advanced use cases.
func (e *Engine) GenerateOpenAPI(identity Identity) *openapi.OpenAPIGenerates OpenAPI specification. Pass an Identity to filter handlers by permissions, or nil for all handlers.
func (e *Engine) Start(host string, port int) errorStarts the HTTP server on the given host and port. Blocks until shutdown.
| Parameter | Type | Description |
|---|---|---|
host |
string |
Host to bind to (empty string for all interfaces) |
port |
int |
Port to listen on |
func (e *Engine) Shutdown(ctx context.Context) errorGracefully shuts down the server, waiting for active requests.
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]| Parameter | Type | Description |
|---|---|---|
path |
string |
URL path with optional parameters (e.g., "/users/{id}") |
fn |
func(*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).
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.
| Parameter | Type | Description |
|---|---|---|
name |
string |
Handler name for logging and OpenAPI operationId |
method |
string |
HTTP method (GET, POST, PUT, PATCH, DELETE) |
path |
string |
URL path with optional parameters (e.g., "/users/{id}") |
fn |
func(*Request[In]) (Out, error) |
Handler function |
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.
func (h *Handler[In, Out]) WithSummary(summary string) *Handler[In, Out]Sets OpenAPI summary (short description).
func (h *Handler[In, Out]) WithDescription(desc string) *Handler[In, Out]Sets OpenAPI description (detailed, supports markdown).
func (h *Handler[In, Out]) WithTags(tags ...string) *Handler[In, Out]Sets OpenAPI tags for grouping operations.
func (h *Handler[In, Out]) WithSuccessStatus(status int) *Handler[In, Out]Sets HTTP status code for successful responses. Default: 200.
func (h *Handler[In, Out]) WithPathParams(params ...string) *Handler[In, Out]Declares required path parameters.
func (h *Handler[In, Out]) WithQueryParams(params ...string) *Handler[In, Out]Declares query parameters.
func (h *Handler[In, Out]) WithResponseHeaders(headers map[string]string) *Handler[In, Out]Sets default response headers.
func (h *Handler[In, Out]) WithErrors(errs ...ErrorDefinition) *Handler[In, Out]Declares errors this handler may return.
func (h *Handler[In, Out]) WithMaxBodySize(size int64) *Handler[In, Out]Sets maximum request body size in bytes. Default: 10MB.
func (h *Handler[In, Out]) WithOutputValidation() *Handler[In, Out]Enables output validation. Disabled by default.
func (h *Handler[In, Out]) WithCodec(codec Codec) *Handler[In, Out]Sets the codec for request/response serialization. Overrides engine default. Default: JSON.
func (h *Handler[In, Out]) WithMiddleware(middleware ...func(http.Handler) http.Handler) *Handler[In, Out]Adds handler-specific middleware.
func (h *Handler[In, Out]) WithAuthentication() *Handler[In, Out]Marks handler as requiring authentication.
func (h *Handler[In, Out]) WithScopes(scopes ...string) *Handler[In, Out]Requires one of the specified scopes (OR logic). Multiple calls create AND logic.
func (h *Handler[In, Out]) WithRoles(roles ...string) *Handler[In, Out]Requires one of the specified roles (OR logic). Multiple calls create AND logic.
func (h *Handler[In, Out]) WithUsageLimit(key string, thresholdFunc func(Identity) int) *Handler[In, Out]Adds usage limit check based on identity stats.
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.
| Parameter | Type | Description |
|---|---|---|
name |
string |
Handler name for logging and documentation |
method |
string |
HTTP method (typically GET or POST) |
path |
string |
URL path with optional parameters |
fn |
func(*Request[In], Stream[Out]) error |
Stream handler function |
StreamHandler supports the same builder methods as Handler:
WithSummary(summary string)- Sets OpenAPI summaryWithDescription(desc string)- Sets OpenAPI descriptionWithTags(tags ...string)- Sets OpenAPI tagsWithPathParams(params ...string)- Declares path parametersWithQueryParams(params ...string)- Declares query parametersWithErrors(errs ...ErrorDefinition)- Declares possible errorsWithMiddleware(middleware ...func(http.Handler) http.Handler)- Adds middlewareWithAuthentication()- Requires authenticationWithScopes(scopes ...string)- Requires scopesWithRoles(roles ...string)- Requires roles
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.
func (s Stream[T]) Send(data T) errorSends a data-only event. Data is JSON-encoded.
func (s Stream[T]) SendEvent(event string, data T) errorSends a named event with data. Allows client-side event filtering.
func (s Stream[T]) SendComment(comment string) errorSends a comment (prefixed with :). Useful for keep-alive.
func (s Stream[T]) Done() <-chan struct{}Returns a channel closed when the client disconnects. Use in select statements to detect disconnection.
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
}| Field | Type | Description |
|---|---|---|
context.Context |
embedded | Request context (deadline, cancellation, values) |
*http.Request |
embedded | Underlying HTTP request (use sparingly) |
Params |
*Params |
Path and query parameters |
Body |
In |
Parsed and validated request body |
Identity |
Identity |
Authenticated identity (or NoIdentity) |
type Params struct {
Path map[string]string
Query map[string]string
}| Field | Type | Description |
|---|---|---|
Path |
map[string]string |
Path parameters (e.g., {id}) |
Query |
map[string]string |
Query parameters |
type NoBody struct{}Empty struct for handlers without request bodies.
type Identity interface {
ID() string
TenantID() string
HasScope(scope string) bool
HasRole(role string) bool
Stats() map[string]int
}| Method | Return | Description |
|---|---|---|
ID() |
string |
Unique identifier |
TenantID() |
string |
Tenant/organization ID |
HasScope(scope) |
bool |
Check if identity has scope |
HasRole(role) |
bool |
Check if identity has role |
Stats() |
map[string]int |
Usage statistics for rate limiting |
type NoIdentity struct{}Default identity for unauthenticated requests. All methods return empty/false values.
type EngineConfig struct {
Host string
Port int
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
}| Field | Type | Default | Description |
|---|---|---|---|
Host |
string |
- | Bind host |
Port |
int |
- | Listen port |
ReadTimeout |
time.Duration |
120s | Read timeout |
WriteTimeout |
time.Duration |
120s | Write timeout |
IdleTimeout |
time.Duration |
120s | Idle timeout |
type EngineSpec struct {
Info openapi.Info
Tags []openapi.Tag
TagGroups []openapi.TagGroup
}OpenAPI specification configuration.
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.
type UsageLimit struct {
Key string
ThresholdFunc func(Identity) int
}Usage limit configuration for rate limiting.
func NewModel[T any]() *ModelScans 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](),
)type Codec interface {
ContentType() string
Marshal(v any) ([]byte, error)
Unmarshal(data []byte, v any) error
}Interface for request/response serialization.
| Method | Return | Description |
|---|---|---|
ContentType() |
string |
MIME type (e.g., "application/json") |
Marshal(v) |
([]byte, error) |
Encodes value to bytes |
Unmarshal(data, v) |
error |
Decodes bytes into value |
type JSONCodec struct{}Default codec implementation using encoding/json.
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.
func NewValidationError(fields []ValidationFieldError) errorCreates a validation error with field-level details. Use this in your Validate() implementations to return structured validation errors that rocco can format correctly.
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"),
)
}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.
| Method | Description |
|---|---|
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 |
- Errors Reference - Error types
- Events Reference - Event signals
- Core Concepts - Usage overview