Reference

Built-in Modules

Redelay ships with 8 production-ready modules: auth, users, groups, health, OpenAPI, AsyncAPI, MCP, and module spec browser — all wired up automatically.

Built-in Modules

Redelay's Go framework ships with 8 production-ready modules that cover the most common needs of any backend application. Each module is self-contained, auto-discovered via blank imports, and fully described through YAML spec files with auto-generated SVG diagrams.

Zero configuration required — every module works out of the box with sensible defaults. Customize behavior via environment variables or programmatic overrides.
For generic infrastructure nodes (Redis, Mongo, HTTP, filesys, SMS, FTP, Postgres, ClickHouse, RabbitMQ) to compose in FlowDSL flows, see Infrastructure Modules and the Node Catalog.

At a glance

ModuleWhat it doesKey features
authJWT authentication & token managementAccess + refresh tokens, OAuth2 password flow, middleware
usersUser CRUD & profile management15-field user entity, pagination, bcrypt hashing
groupsGroups & permission resolutionRole-based permissions, group membership
healthHealth check endpoint/health readiness probe
openapiOpenAPI 3.0 spec & API docs UIScalar / Swagger UI / Redoc, auto-generated spec
asyncapiAsyncAPI 2.6 spec & event browser UIAuto-generated from event definitions, AsyncAPI Studio
mcpModel Context Protocol serverTool auto-discovery from modules
modspecModule spec browser & diagramsInteractive hub with routes, events, consumers + links to OpenAPI & AsyncAPI

Quick start

Enable modules with blank imports — the framework auto-discovers and wires them:

go
import (
    _ "github.com/redelay/go-framework/modules/auth"
    _ "github.com/redelay/go-framework/modules/users"
    _ "github.com/redelay/go-framework/modules/groups"
    _ "github.com/redelay/go-framework/modules/health"
    _ "github.com/redelay/go-framework/modules/openapi"
    _ "github.com/redelay/go-framework/modules/asyncapi"
    _ "github.com/redelay/go-framework/modules/mcp"
    _ "github.com/redelay/go-framework/modules/modspec"
)

That's it. All routes, middleware, and cross-module dependencies are resolved automatically.


auth

JWT authentication with refresh token rotation, OAuth2 password flow, and fine-grained middleware.

The auth module handles the complete authentication lifecycle — from login to token refresh to revocation. It supports both JSON and application/x-www-form-urlencoded (OAuth2 password flow) for the login endpoint, making it compatible with Scalar, Swagger UI, and any OAuth2 client.

Routes

MethodPathDescription
POST/auth/loginAuthenticate and receive access + refresh tokens
POST/auth/refreshRotate the refresh token
POST/auth/revokeRevoke a refresh token

Events

EventTrigger
auth.loginSuccessful authentication
auth.login_failedFailed login attempt (bad credentials)
auth.token_refreshedToken successfully rotated
auth.token_revokedRefresh token revoked

Middleware

go
// Require valid JWT on all routes in a group
r.Use(auth.AuthMiddleware)

// Optional — populate user context if token present
r.Use(auth.OptionalAuth)

// Restrict to superusers
r.Use(auth.RequireSuperuser)

// Check specific permission
r.Use(auth.RequirePermission("users.write"))

Configuration

VariableDefaultDescription
AUTH_JWT_SECRETrequiredSecret key for JWT signing
AUTH_JWT_ALGORITHMHS256JWT signing algorithm
AUTH_ACCESS_TOKEN_TTL_MINUTES30Access token lifetime
AUTH_REFRESH_TOKEN_TTL_DAYS7Refresh token lifetime
AUTH_JWT_ISSUERredelayJWT issuer claim
AUTH_MAX_REFRESH_TOKENS5Max active refresh tokens per user
AUTH_TOKEN_COLLECTIONtokensMongoDB collection for refresh tokens

Cross-module integration

The auth module automatically discovers and integrates with:

  • users module — as a LookupProvider for credential verification
  • groups module — as a PermissionsProvider for permission-based authorization

users

Full user CRUD with a rich 15-field entity, pagination, password hashing, and event emission.

The users module provides a complete user management system with create, read, update, delete, and list operations. Every mutation emits a typed event, making it easy to trigger downstream workflows.

Entity: User

FieldTypeDescription
idObjectIDUnique identifier
emailstringUnique, validated email address
full_namestringDisplay name
first_namestringGiven name
last_namestringFamily name
is_activebooleanAccount active flag
is_superuserbooleanSuperuser privileges
email_validatedbooleanEmail verification status
totp_enabledbooleanTwo-factor auth enabled
profile_picturestringAvatar URL
oauth_providerstringExternal auth provider
user_groupsstringGroup membership IDs
last_login_atdatetimeLast successful login
created_atdatetimeAccount creation time
updated_atdatetimeLast modification time

Routes

MethodPathDescription
GET/users/meCurrent user profile
GET/users/List users (paginated)
POST/users/Create a new user
GET/users/{id}Get user by ID
PATCH/users/{id}Update user
DELETE/users/{id}Delete user

Events

EventTrigger
users.user_createdNew user registered
users.user_updatedUser profile modified
users.user_deletedUser account removed

CRUD operations

All operations are declared in the module spec and support:

  • Create — with password hashing and email uniqueness validation
  • Read — single user by ID
  • Update — partial updates with field-level validation
  • Delete — soft or hard delete
  • List — paginated with configurable page size

Configuration

VariableDefaultDescription
USERS_COLLECTIONusersMongoDB collection name
USERS_DEFAULT_PAGE_SIZE20Default pagination size
USERS_MAX_PAGE_SIZE100Maximum allowed page size
USERS_REQUIRE_EMAIL_VALIDATIONfalseRequire verified email

groups

Role-based group management with permission resolution and user membership.

The groups module provides user groups with associated permissions. When combined with the auth module's RequirePermission middleware, it enables fine-grained role-based access control (RBAC).

Entity: UserGroup

FieldTypeDescription
idObjectIDUnique identifier
namestringGroup name
descriptionstringGroup purpose
permissionsstringPermission strings (e.g., users.write)
is_activebooleanGroup active flag
created_atdatetimeCreation time
updated_atdatetimeLast modification

Events

EventTrigger
groups.group_createdNew group created
groups.group_updatedGroup modified
groups.group_deletedGroup removed

CRUD operations

Full CRUD with create, read, update, delete, and list — all with event emission.

Configuration

VariableDefaultDescription
GROUPS_COLLECTIONgroupsMongoDB collection name

How permissions work

text
User → belongs to Groups → each Group has Permissions → auth middleware checks Permissions
go
// In your routes:
r.Handle("DELETE", "/{id}", handler,
    modules.Security("BearerAuth"),
    modules.RequirePermission("users.delete"),
)

health

Simple health check endpoint for container orchestration readiness probes.

Returns a JSON response indicating the service is running and ready to accept requests.

shell
curl http://localhost:8080/api/v1/health
# {"status": "ok"}

No configuration required. Ideal for Kubernetes readinessProbe and livenessProbe.


openapi

Auto-generated OpenAPI 3.0 spec with interactive API documentation UI.

The OpenAPI module introspects all registered routes and their metadata (request bodies, responses, security requirements) to produce a complete OpenAPI 3.0 specification. It serves this spec as JSON and renders an interactive UI for exploring and testing the API.

Endpoints

PathDescription
/openapi.jsonOpenAPI 3.0 spec (JSON)
/referenceInteractive API documentation UI

UI providers

Choose your preferred documentation interface:

ProviderSettingDescription
ScalarOPENAPI_UI=scalarModern, beautiful API reference (default)
Swagger UIOPENAPI_UI=swaggerClassic Swagger interface
RedocOPENAPI_UI=redocClean read-focused documentation
DisabledOPENAPI_UI=disabledJSON spec only, no UI

How schemas are generated

Route handlers declare metadata using functional options:

go
r.Handle("POST", "/", handler,
    modules.Summary("Create user"),
    modules.Body(UserCreateInput{}),
    modules.Response(201, "User created", UserResponse{}),
    modules.Response(400, "Bad request", modules.RedelayErrorResponse{}),
    modules.Security("BearerAuth"),
)

The SchemaRegistry converts Go structs to JSON Schema using reflection:

  • json tags → field names
  • validate tags → constraints (required, email, min, max)
  • Pointer types → nullable
  • time.Time → date-time format
  • Slices, maps, embedded structs → proper schema composition

Configuration

VariableDefaultDescription
OPENAPI_UIscalarUI provider selection
OPENAPI_SPEC_PATH/openapi.jsonJSON spec path
OPENAPI_UI_PATH/referenceUI page path

asyncapi

Auto-generated AsyncAPI 2.6 spec from all registered events, served with AsyncAPI Studio.

The AsyncAPI module is the event-contract equivalent of the OpenAPI module — it introspects every module's Events() and Consumers() declarations to produce a complete AsyncAPI 2.6 specification and serve an interactive UI.

Full reference: AsyncAPI Module

Endpoints

PathDescription
/asyncapi.jsonAsyncAPI 2.6 spec (YAML, Content-Type: application/yaml)
/asyncapiAsyncAPI Studio — interactive event browser

How events become channels

Each ir.Event returned by a module's Events() method becomes an AsyncAPI channel:

text
Module.Events() → ir.Event{Name: "order.created", Topic: "order.created", Payload: ...}

asyncapi: "2.6.0"
channels:
  order.created:
    publish:
      operationId: order.created
      message:
        payload:
          $ref: '#/components/schemas/OrderCreatedPayload'

Consumer registrations produce subscribe operations with Kafka groupId bindings. Payload packets with named fields produce components/schemas entries.

Configuration

VariableDefaultDescription
ASYNCAPI_UIstudioUI provider (studio or disabled)
ASYNCAPI_SPEC_PATH/asyncapi.jsonYAML spec path
ASYNCAPI_UI_PATH/asyncapiStudio UI path

mcp

Model Context Protocol server with automatic tool discovery from registered modules.

The MCP module exposes your framework's capabilities as tools that AI assistants can invoke. It speaks the MCP Streamable HTTP transport (protocol 2025-03-26) — compatible with VS Code, Claude Desktop, Cursor, and other MCP clients.

Endpoint

MethodPathDescription
POST/mcpMCP JSON-RPC endpoint (Streamable HTTP transport)

What gets discovered

  1. Introspection tools (9) — list_modules, describe_module, list_flowdsl_nodes, describe_flowdsl_node, list_events, describe_event, list_packets, describe_packet, search_redelay
  2. Developer tools (5) — validate_flowdsl, validate_module, scaffold_module, list_api_routes, explain_flowdsl_node
  3. Route tools — every HTTP route from RoutesProvider modules becomes a callable tool
  4. Module-contributed tools — any module implementing MCPProvider contributes its own tools and resources

Extending MCP from your module

Implement MCPProvider to contribute tools:

go
func (m *Module) MCPTools() []modules.MCPTool {
    return []modules.MCPTool{
        {
            Name:        "my_tool",
            Description: "Does something useful for AI assistants",
            InputSchema: map[string]any{
                "type": "object",
                "properties": map[string]any{
                    "query": map[string]any{"type": "string"},
                },
            },
            Handler: func(ctx context.Context, args map[string]any) (any, error) {
                // your logic here
                return result, nil
            },
        },
    }
}

func (m *Module) MCPResources() []modules.MCPResource { return nil }

Your tools appear in tools/list as soon as your module is blank-imported.

IDE setup

Add to .vscode/mcp.json:

json
{
  "servers": {
    "my-app": {
      "type": "http",
      "url": "http://localhost:8000/mcp"
    }
  }
}

modspec

Interactive module spec browser with SVG diagrams and YAML definitions.

The modspec module provides a visual overview of all registered modules — similar to how the OpenAPI module provides interactive API reference.

Endpoints

PathDescription
/modules.jsonJSON array of all module specs (includes SVG + YAML)
/modulesInteractive HTML browser with diagrams

Features

  • Module cards — expandable panels for each registered module with badges showing route/event/consumer counts
  • Routes tab — color-coded HTTP method badges with full paths (sourced from OpenAPI route discovery)
  • Events tab — list of published events with topic and description
  • Consumers tab — list of consumed topics with consumer group IDs
  • SVG diagrams — auto-generated visual diagrams showing entities, events, config, CRUD, settings, and dependencies
  • YAML specs — full module definition with copy button
  • Top nav links — quick links to /reference (OpenAPI UI) and /asyncapi (AsyncAPI Studio)
  • Dark mode — automatic theme switching
  • Zero external dependencies — fully self-contained HTML page

modules.json schema

The /modules.json endpoint returns a JSON array, with each entry including:

json
{
  "name": "auth",
  "description": "...",
  "version": "1.0.0",
  "routes": [
    { "method": "POST", "path": "/api/v1/auth/login", "summary": "Login" }
  ],
  "events": [
    { "name": "auth.login", "topic": "auth.login", "description": "Successful authentication" }
  ],
  "consumers": [],
  "svg": "...",
  "yaml": "..."
}

Configuration

VariableDefaultDescription
MODSPEC_SPEC_PATH/modules.jsonJSON spec path
MODSPEC_UI_PATH/modulesUI page path
OPENAPI_UI_PATH/referenceOpenAPI UI link in the top nav
ASYNCAPI_UI_PATH/asyncapiAsyncAPI Studio link in the top nav
ROUTE_PREFIX/api/v1Prepended to route paths in the UI

Module dependency graph

The built-in modules form a clean dependency tree:

text
auth ──→ users (credential lookup)
  │
  └──→ groups (permission resolution)

openapi  ──→ reads route metadata from all modules     → /openapi.json + /reference
asyncapi ──→ reads event/consumer IR from all modules  → /asyncapi.json + /asyncapi
mcp      ──→ discovers tools from all modules          → /mcp
modspec  ──→ reads IR + routes from all modules        → /modules.json + /modules
                (links to openapi + asyncapi UIs)

health (standalone)

Every module is optional — import only what you need. Dependencies are resolved automatically at bootstrap.

The three spec layers

SpecPathCovers
OpenAPI/openapi.json + /referenceHTTP routes, request/response schemas, security
AsyncAPI/asyncapi.json + /asyncapiEvent channels, message schemas, consumer groups
ModSpec/modules.json + /modulesModule architecture — entities, CRUD, config, settings, flows; links to both above

Creating custom modules

See the Creating a Go Module guide and the Module Definition Files reference for defining your own modules with YAML specs, JSON Schema validation, and auto-generated diagrams.