Router

Introduction

Comprehensive HTTP routing system with advanced features

Forge provides a powerful and flexible routing system that supports multiple backends, middleware, streaming, API documentation, and advanced features. The router is designed to be extensible, performant, and developer-friendly.

Router Interface

The router interface provides a clean, consistent API regardless of the underlying implementation:

type Router interface {
    // HTTP Methods - register routes
    GET(path string, handler any, opts ...RouteOption) error
    POST(path string, handler any, opts ...RouteOption) error
    PUT(path string, handler any, opts ...RouteOption) error
    DELETE(path string, handler any, opts ...RouteOption) error
    PATCH(path string, handler any, opts ...RouteOption) error
    OPTIONS(path string, handler any, opts ...RouteOption) error
    HEAD(path string, handler any, opts ...RouteOption) error

    // Grouping - organize routes
    Group(prefix string, opts ...GroupOption) Router

    // Middleware - wrap handlers
    Use(middleware ...Middleware)

    // Controller registration
    RegisterController(controller Controller) error

    // Lifecycle
    Start(ctx context.Context) error
    Stop(ctx context.Context) error

    // HTTP serving
    ServeHTTP(w http.ResponseWriter, r *http.Request)
    Handler() http.Handler

    // Inspection
    Routes() []RouteInfo
    RouteByName(name string) (RouteInfo, bool)
    RoutesByTag(tag string) []RouteInfo
    RoutesByMetadata(key string, value any) []RouteInfo

    // OpenAPI
    OpenAPISpec() *OpenAPISpec

    // AsyncAPI
    AsyncAPISpec() *AsyncAPISpec

    // Streaming
    WebSocket(path string, handler WebSocketHandler, opts ...RouteOption) error
    EventStream(path string, handler SSEHandler, opts ...RouteOption) error

    // WebTransport
    WebTransport(path string, handler WebTransportHandler, opts ...RouteOption) error
    EnableWebTransport(config WebTransportConfig) error
    StartHTTP3(addr string, tlsConfig *tls.Config) error
    StopHTTP3() error
}

Key Features

🚀 Multiple Backend Support

  • BunRouter (Recommended): High performance, modern API
  • Chi Router: Clean, composable middleware-first design
  • HTTPRouter: Extremely fast route matching
  • Custom Adapters: Extensible adapter system

📡 Streaming Support

  • WebSocket: Bidirectional real-time communication
  • Server-Sent Events (SSE): Real-time data streaming
  • WebTransport: Modern web transport protocol with HTTP/3

📚 API Documentation

  • OpenAPI 3.0: Automatic specification generation
  • AsyncAPI 3.0: Event-driven API documentation
  • Interactive Documentation: Built-in Swagger UI and ReDoc

🔧 Advanced Features

  • Route Groups: Organize routes with shared middleware
  • Middleware System: Flexible middleware chaining
  • Path Parameters: Dynamic route parameters
  • Route Inspection: Runtime route information
  • Error Handling: Centralized error management

Quick Start

Basic Routing

package main

import (
    "log"
    "github.com/xraph/forge"
)

func main() {
    app := forge.NewApp(forge.AppConfig{
        Name:    "my-api",
        Version: "1.0.0",
    })

    // Basic routes
    app.Router().GET("/", func(ctx forge.Context) error {
        return ctx.JSON(200, map[string]string{
            "message": "Hello, Forge!",
        })
    })

    app.Router().POST("/users", func(ctx forge.Context) error {
        var user CreateUserRequest
        if err := ctx.BindJSON(&user); err != nil {
            return forge.BadRequest("invalid JSON")
        }
        
        // Process user creation
        return ctx.JSON(201, map[string]string{"id": "123"})
    })

    // Route with path parameters
    app.Router().GET("/users/:id", func(ctx forge.Context) error {
        id := ctx.Param("id")
        return ctx.JSON(200, map[string]string{"id": id})
    })

    // Start server
    if err := app.Run(); err != nil {
        log.Fatal(err)
    }
}

Route Groups

// API v1 group
apiV1 := app.Router().Group("/api/v1")
apiV1.GET("/users", getUsersHandler)
apiV1.POST("/users", createUserHandler)
apiV1.GET("/users/:id", getUserHandler)

// Admin group with authentication
admin := app.Router().Group("/admin", forge.WithGroupMiddleware(authMiddleware))
admin.GET("/dashboard", dashboardHandler)
admin.POST("/settings", updateSettingsHandler)

Middleware

// Global middleware
app.Router().Use(
    forge.LoggerMiddleware(),
    forge.RecoveryMiddleware(),
    forge.CORSMiddleware(),
)

// Route-specific middleware
app.Router().GET("/protected", handler, 
    forge.WithMiddleware(authMiddleware, rateLimitMiddleware),
)

Router Adapters

import "github.com/xraph/forge/extras"

router := forge.NewRouter(
    forge.WithAdapter(extras.NewBunRouterAdapter()),
)

Features:

  • Fast route matching
  • Modern API design
  • Path parameters: /users/:id
  • Wildcard routes: /files/*

Chi Router

router := forge.NewRouter(
    forge.WithAdapter(extras.NewChiAdapter()),
)

Features:

  • Middleware-first design
  • Sub-router mounting
  • Path parameters: /users/{id}

HTTPRouter

router := forge.NewRouter(
    forge.WithAdapter(extras.NewHTTPRouterAdapter()),
)

Features:

  • Fastest route matching
  • Minimal allocations
  • Path parameters: /users/:id

Configuration

Router Options

router := forge.NewRouter(
    forge.WithAdapter(extras.NewBunRouterAdapter()),
    forge.WithContainer(container),
    forge.WithLogger(logger),
    forge.WithErrorHandler(errorHandler),
    forge.WithRecovery(),
    forge.WithOpenAPI(forge.OpenAPIConfig{
        Title:   "My API",
        Version: "1.0.0",
    }),
    forge.WithAsyncAPI(forge.AsyncAPIConfig{
        Title:   "Event API",
        Version: "1.0.0",
    }),
)

Route Options

app.Router().GET("/users", handler,
    forge.WithName("getUsers"),
    forge.WithSummary("Get all users"),
    forge.WithDescription("Retrieves a list of all users"),
    forge.WithTags("users"),
    forge.WithTimeout(30*time.Second),
    forge.WithMetadata("version", "v1"),
)

Best Practices

  1. Use Route Groups: Organize related routes with shared middleware
  2. Apply Middleware Strategically: Use global middleware for common concerns
  3. Document Routes: Use OpenAPI options for better documentation
  4. Handle Errors: Implement proper error handling middleware
  5. Use Appropriate Adapters: Choose the right adapter for your use case
  6. Streaming: Use WebSocket/SSE for real-time features
  7. Performance: Consider HTTPRouter for high-throughput applications

Performance Considerations

AdapterPerformanceFeaturesUse Case
BunRouter⚡⚡⚡ HighModern, full-featuredRecommended for most apps
Chi⚡⚡ GoodMiddleware-focusedApps with complex middleware
HTTPRouter⚡⚡⚡ HighestMinimal, fastHigh-throughput APIs

For detailed information about specific router features, see the individual pages in the navigation menu.

How is this guide?

Last updated on