rtr

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2025 License: MIT Imports: 9 Imported by: 0

README

RTR Router

A high-performance, flexible, and feature-rich HTTP router for Go applications with support for middleware chains, route grouping, and domain-based routing.

Tests Status Go Report Card PkgGoDev License GitHub release Go version codecov

Features

  • High Performance: Optimized for speed with minimal allocations
  • RESTful Routing: Intuitive API for defining RESTful endpoints
  • Middleware Support: Flexible middleware chaining with before/after execution
  • Route Groups: Organize routes with shared prefixes and middleware
  • Domain-Based Routing: Handle different domains/subdomains with ease
  • Multiple Handler Types: Support for various response types (JSON, HTML, XML, etc.)
  • Context Support: Built-in context support for request-scoped values
  • Standard Library Compatible: Implements http.Handler for seamless integration
  • Comprehensive Testing: High test coverage with extensive test cases

Installation

go get github.com/dracory/rtr

Quick Start

package main

import (
	"net/http"
	"github.com/dracory/rtr"
)

func main() {
	r := rtr.NewRouter()
	r.AddRoute(rtr.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, World!"))
	}))

	http.ListenAndServe(":8080", r)
}

Documentation

For comprehensive documentation, see the docs/ directory in this repository or the package reference on PkgGoDev. Key guides:

Examples

Explore complete, runnable examples in the examples directory.

Benchmarks

Performance comparison with other popular routers:

BenchmarkRouter/Static-8     5000000   300 ns/op   32 B/op   1 allocs/op
BenchmarkRouter/Param-8      3000000   450 ns/op  160 B/op   4 allocs/op
BenchmarkRouter/Regexp-8     2000000   700 ns/op  320 B/op   6 allocs/op

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

MIT License - see LICENSE for details.

Acknowledgments

  • Inspired by httprouter and chi
  • Thanks to all contributors
  • Thanks to all contributors
  • Route Groups: Group related routes with shared prefixes and middleware
  • Middleware Support:
    • Pre-route (before) middleware
    • Post-route (after) middleware
    • Support at router, domain, group, and individual route levels
    • Built-in panic recovery middleware
  • Nested Groups: Create hierarchical route structures with nested groups
  • Flexible API: Chainable methods for intuitive route and group configuration
  • Standard Interface: Implements http.Handler interface for seamless integration
  • Declarative Configuration: Define routes using configuration objects for better maintainability and tooling support

Middleware

Built-in Middleware

The router comes with several built-in middleware components. For complete documentation on available middleware and usage examples, see Built-in Middleware Documentation.

  • Recovery: Catches panics and returns 500 errors
  • CORS: Handles Cross-Origin Resource Sharing
  • Logging: Request/response logging
  • Rate Limiting: Request rate limiting
  • Request ID: Adds unique IDs to requests
  • Security Headers: Adds security-related HTTP headers
  • Timeouts: Request timeout handling

Example of adding middleware:

// Add recovery and logging middleware (named middlewares)
r.AddBeforeMiddlewares([]rtr.MiddlewareInterface{
    rtr.NewMiddleware(rtr.WithName("Recovery"), rtr.WithHandler(middlewares.RecoveryMiddleware)),
    rtr.NewMiddleware(rtr.WithName("Logger"), rtr.WithHandler(middlewares.Logger())),
})
Execution order (before/after)

The middleware execution sequence strictly follows:

  • globals before → domains before → groups before → routes before
  • handler
  • routes after → groups after → domains after → globals after

Core Components

Router

The main router component that handles HTTP requests and manages routes and groups.

router := rtr.NewRouter()
Routes

Individual route definitions that specify HTTP method, path, and handler.

// Using shortcut methods
route := rtr.Get("/users", handleUsers)         // Exact match: /users
route := rtr.Post("/users", createUser)         // Exact match: /users
route := rtr.Put("/users/123", updateUser)      // Exact match required: /users/123
route := rtr.Delete("/users/123", deleteUser)   // Exact match required: /users/123

// Using method chaining
route := rtr.NewRoute()
    .SetMethod("GET")
    .SetPath("/users")
    .SetHandler(handleUsers)

Handler Types

The router supports multiple handler types that provide different levels of convenience and functionality. Each handler type is designed for specific use cases and automatically handles appropriate HTTP headers.

Route Handlers

The router supports multiple handler types for different response formats, each automatically handling appropriate HTTP headers. See Route Handlers Documentation for complete details.

Available Handler Types
  1. Standard Handler - Full HTTP control
  2. String/Text Handlers - For plain text responses
  3. Web Content Handlers - HTML, JSON, XML with auto content-type
  4. Asset Handlers - CSS, JavaScript for static files
  5. Error Handler - Centralized error handling
Quick Example
// JSON response
rtr.GetJSON("/api/status", func(w http.ResponseWriter, r *http.Request) string {
    return `{"status":"ok"}`
})

// HTML response with parameters
rtr.GetHTML("/user/:id", func(w http.ResponseWriter, r *http.Request) string {
    userID := rtr.MustGetParam(r, "id")
    return fmt.Sprintf("<h1>User %s</h1>", userID)
})

For complete documentation, examples, and best practices, see Route Handlers Documentation.

StringHandler

A generic string handler that returns content without setting any headers automatically. Useful when you need full control over headers but want the convenience of returning a string:

r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/custom").
    SetStringHandler(func(w http.ResponseWriter, req *http.Request) string {
        w.Header().Set("Content-Type", "text/custom")
        w.Header().Set("X-Custom-Header", "value")
        return "Custom content with custom headers"
    }))
HTMLHandler

Returns HTML content and automatically sets Content-Type: text/html; charset=utf-8:

r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/page").
    SetHTMLHandler(func(w http.ResponseWriter, req *http.Request) string {
        return `<!DOCTYPE html>
<html>
<head><title>My Page</title></head>
<body><h1>Hello World!</h1></body>
</html>`
    }))
JSONHandler

Returns JSON content and automatically sets Content-Type: application/json:

r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/api/users").
    SetJSONHandler(func(w http.ResponseWriter, req *http.Request) string {
        return `{
    "users": [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"}
    ]
}`
    }))
CSSHandler

Returns CSS content and automatically sets Content-Type: text/css:

r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/styles.css").
    SetCSSHandler(func(w http.ResponseWriter, req *http.Request) string {
        return `body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}

h1 {
    color: #333;
    border-bottom: 2px solid #007acc;
}`
    }))
XMLHandler

Returns XML content and automatically sets Content-Type: application/xml:

r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/api/data.xml").
    SetXMLHandler(func(w http.ResponseWriter, req *http.Request) string {
        return `<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user id="1">
        <name>Alice</name>
        <email>alice@example.com</email>
    </user>
</users>`
    }))
TextHandler

Returns plain text content and automatically sets Content-Type: text/plain; charset=utf-8:

r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/robots.txt").
    SetTextHandler(func(w http.ResponseWriter, req *http.Request) string {
        return `User-agent: *
Disallow: /admin/
Allow: /

Sitemap: https://example.com/sitemap.xml`
    }))
JSHandler

Returns JavaScript content and automatically sets Content-Type: application/javascript:

r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/script.js").
    SetJSHandler(func(w http.ResponseWriter, req *http.Request) string {
        return `console.log("Hello from RTR Router!");

function initApp() {
    document.addEventListener('DOMContentLoaded', function() {
        console.log('App initialized');
    });
}

initApp();`
    }))
ErrorHandler

Handles errors by returning an error value. If the error is nil, no content is written. If an error is returned, the error message is written to the response:

r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/might-fail").
    SetErrorHandler(func(w http.ResponseWriter, req *http.Request) error {
        // Some logic that might fail
        if someCondition {
            return errors.New("something went wrong")
        }
        // Success case - no error, no output
        return nil
    }))
Handler Combinations

You can set multiple handlers on a single route. The router will use the highest priority handler that is set:

// This route has both HTML and JSON handlers
// HTMLHandler takes priority and will be used
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/content").
    SetHTMLHandler(func(w http.ResponseWriter, req *http.Request) string {
        return "<h1>HTML Content</h1>"  // This will be used
    }).
    SetJSONHandler(func(w http.ResponseWriter, req *http.Request) string {
        return `{"message": "JSON Content"}`  // This will be ignored
    }))
Dynamic Content with Parameters

All handler types work seamlessly with path parameters:

// HTML handler with parameters
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/user/:id").
    SetHTMLHandler(func(w http.ResponseWriter, req *http.Request) string {
        userID := rtr.MustGetParam(req, "id")
        return fmt.Sprintf(`<h1>User Profile</h1><p>User ID: %s</p>`, userID)
    }))

// JSON handler with parameters
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/api/user/:id").
    SetJSONHandler(func(w http.ResponseWriter, req *http.Request) string {
        userID := rtr.MustGetParam(req, "id")
        return fmt.Sprintf(`{"user": {"id": "%s", "name": "User %s"}}`, userID, userID)
    }))
Response Helper Functions

The router provides response helper functions that you can use directly in standard handlers:

// Using response helpers in a standard handler
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/manual").
    SetHandler(func(w http.ResponseWriter, req *http.Request) {
        // These functions set appropriate headers and write content
        rtr.JSONResponse(w, req, `{"message": "Hello JSON"}`)
        // or
        rtr.HTMLResponse(w, req, "<h1>Hello HTML</h1>")
        // or
        rtr.CSSResponse(w, req, "body { color: red; }")
        // or
        rtr.XMLResponse(w, req, "<?xml version='1.0'?><root></root>")
        // or
        rtr.TextResponse(w, req, "Hello Text")
        // or
        rtr.JSResponse(w, req, "console.log('Hello JS');")
    }))
Groups

Route groups that share common prefixes and middleware.

group := rtr.NewGroup()
    .SetPrefix("/api")
    .AddRoute(route)

Usage Examples

Basic Router Setup
r := rtr.NewRouter()

// Add routes using shortcut methods
r.AddRoute(rtr.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}))

// Add routes using method chaining
r.AddRoute(rtr.NewRoute()
    .SetMethod("GET")
    .SetPath("/users")
    .SetHandler(handleUsers))
Using Route Groups
// Create an API group
apiGroup := rtr.NewGroup().SetPrefix("/api")

// Add routes to the group
apiGroup.AddRoute(rtr.NewRoute()
    .SetMethod("GET")
    .SetPath("/users")
    .SetHandler(handleUsers))

// Add the group to the router
r.AddGroup(apiGroup)
Adding Middleware
// Router-level middleware
r.AddBeforeMiddlewares([]rtr.MiddlewareInterface{
    rtr.NewMiddleware(rtr.WithName("Logging"), rtr.WithHandler(loggingMiddleware)),
    rtr.NewMiddleware(rtr.WithName("Auth"), rtr.WithHandler(authenticationMiddleware)),
})

// Group-level middleware
apiGroup.AddBeforeMiddlewares([]rtr.MiddlewareInterface{
    rtr.NewMiddleware(rtr.WithName("APIKey"), rtr.WithHandler(apiKeyMiddleware)),
})

// Route-level middleware
route.AddBeforeMiddlewares([]rtr.MiddlewareInterface{
    rtr.NewMiddleware(rtr.WithName("SpecificRoute"), rtr.WithHandler(specificRouteMiddleware)),
})

Declarative API

In addition to the imperative API shown above, the router also supports a declarative configuration approach that allows you to define your entire routing structure as data structures.

Basic Declarative Usage
config := rtr.RouterConfig{
    Name: "My API",
    Routes: []rtr.RouteConfig{
        rtr.GET("/", homeHandler).WithName("Home"),
        rtr.POST("/users", createUserHandler).WithName("Create User"),
    },
    Groups: []rtr.GroupConfig{
        rtr.Group("/api",
            rtr.GET("/users", usersHandler).WithName("List Users"),
            rtr.GET("/products", productsHandler).WithName("List Products"),
        ).WithName("API Group"),
    },
}

router := rtr.NewRouterFromConfig(config)
Declarative Route Helpers
// HTTP method helpers
rtr.GET("/users", handler)     // GET route
rtr.POST("/users", handler)    // POST route
rtr.PUT("/users/:id", handler) // PUT route
rtr.DELETE("/users/:id", handler) // DELETE route

// Chainable configuration
rtr.GET("/users", handler).
    WithName("List Users").
    WithBeforeMiddleware(rtr.NewAnonymousMiddleware(authMiddleware)).
    WithMetadata("version", "1.0")
Hybrid Approach

You can mix declarative and imperative approaches:

// Start with declarative configuration
config := rtr.RouterConfig{
    Routes: []rtr.RouteConfig{
        rtr.GET("/", homeHandler).WithName("Home"),
    },
}
router := rtr.NewRouterFromConfig(config)

// Add imperative routes
router.AddRoute(rtr.Get("/health", healthHandler).SetName("Health"))
Benefits of Declarative API
  • Serializable: Configuration can be exported to JSON/YAML
  • Testable: Easier to unit test route configurations
  • Readable: Clear structure and intent
  • Tooling-friendly: Better IDE support and validation

Path Parameters

The router supports flexible path parameter extraction with the following features:

Basic Parameters

Extract values from URL paths using :param syntax:

// Define a route with parameters
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/users/:id").
    SetHandler(func(w http.ResponseWriter, r *http.Request) {
        // Get a required parameter
        id := rtr.MustGetParam(r, "id")
        
        // Or safely get an optional parameter
        if name, exists := rtr.GetParam(r, "name"); exists {
            // Parameter exists
        }
    }))
Optional Parameters

Mark parameters as optional with ?:

// Both /articles/tech and /articles/tech/123 will match
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/articles/:category/:id?").
    SetHandler(handleArticle))
Greedy Parameters (capture the remainder)

Use :name... as the last segment to capture all remaining path segments into a single parameter. This mirrors the standard library pattern like /files/{pathname...}.

// Matches both of the following and captures the remainder into "pathname":
//   /files/images/photo.jpg         -> pathname = "images/photo.jpg"
//   /files/user/albums/2025/img.png -> pathname = "user/albums/2025/img.png"
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/files/:pathname...").
    SetHandler(func(w http.ResponseWriter, r *http.Request) {
        pathname := rtr.MustGetParam(r, "pathname")
        _ = pathname // use it
    }))

// Example for thumbnail routes: /th/:extension/:size/:quality/:path...
//   /th/jpg/300x300/80/avatar.png        -> path = "avatar.png"
//   /th/jpg/300x300/80/user/avatar.png   -> path = "user/avatar.png"
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/th/:extension/:size/:quality/:path...").
    SetHandler(func(w http.ResponseWriter, r *http.Request) {
        ext := rtr.MustGetParam(r, "extension")
        size := rtr.MustGetParam(r, "size")
        quality := rtr.MustGetParam(r, "quality")
        tail := rtr.MustGetParam(r, "path")
        _, _, _, _ = ext, size, quality, tail
    }))
Wildcard/Catch-all Routes

Use /* to allow any suffix after a base path. This is a non-capturing catch-all; if you need the remainder, use a greedy parameter as shown above.

// Matches any path starting with /static/ (non-capturing)
// e.g., /static/js/main.js, /static/css/style.css
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/static/*").
    SetHandler(func(w http.ResponseWriter, r *http.Request) {
        // Use a greedy parameter instead if you need the suffix
        w.WriteHeader(http.StatusOK)
    }))
Getting All Parameters

Retrieve all path parameters as a map:

params := rtr.GetParams(r)
// params is a map[string]string of all path parameters

Path Matching Rules

The router uses the following matching rules:

  • Paths are matched exactly as defined, with parameter placeholders
  • Required parameters must be present in the request path
  • Optional parameters can be omitted
  • Parameter names must be unique within a route
  • A greedy parameter (:name...) must be the last segment in the path

Domain-based Routing

The router supports domain-based routing, allowing you to define routes that only match specific domain names or patterns.

Creating a Domain
// Create a domain with exact match
domain := rtr.NewDomain("example.com")

// Create a domain with wildcard subdomain matching
wildcardDomain := rtr.NewDomain("*.example.com")

// Create a domain that matches multiple patterns
multiDomain := rtr.NewDomain("example.com", "api.example.com", "*.example.org")
Adding Routes to a Domain
// Create a new domain
domain := rtr.NewDomain("api.example.com")

// Add routes directly to the domain
domain.AddRoute(rtr.Get("/users", handleUsers))

// Add multiple routes at once
domain.AddRoutes([]rtr.RouteInterface{
    rtr.Get("/users", handleUsers),
    rtr.Post("/users", createUser),
})
Adding Groups to a Domain
// Create a domain
domain := rtr.NewDomain("api.example.com")

// Create an API group
apiGroup := rtr.NewGroup().SetPrefix("/v1")

// Add routes to the group
apiGroup.AddRoute(rtr.Get("/products", handleProducts))

// Add the group to the domain
domain.AddGroup(apiGroup)

// Add the domain to the router
r := rtr.NewRouter()
r.AddDomain(domain)
Domain Matching

Domains are matched against the Host header of incoming requests. The matching supports:

Basic Domain Matching
  • Exact matches (example.com)
  • Wildcard subdomains (*.example.com)
  • Multiple patterns per domain
Port Matching
  • No port in pattern: Matches any port on that host

    domain := rtr.NewDomain("example.com")  // Matches example.com, example.com:8080, example.com:3000, etc.
    
  • Exact port: Requires exact port match

    domain := rtr.NewDomain("example.com:8080")  // Only matches example.com:8080
    
  • Wildcard port: Matches any port on that host

    domain := rtr.NewDomain("example.com:*")  // Matches example.com with any port
    
  • IPv4 and IPv6 support:

    // IPv4 with port
    ipv4Domain := rtr.NewDomain("127.0.0.1:8080")  // Matches 127.0.0.1:8080
    
    // IPv6 with port (note the square brackets)
    ipv6Domain := rtr.NewDomain("[::1]:8080")  // Matches [::1]:8080
    
Examples
// Match any port on example.com
anyPort := rtr.NewDomain("example.com")

// Match only port 8080
exactPort := rtr.NewDomain("example.com:8080")

// Match any subdomain on any port
wildcardSubdomain := rtr.NewDomain("*.example.com:*")

// Match localhost on any port
localhost := rtr.NewDomain("localhost:*")

// Match IPv6 localhost on port 3000
ipv6Localhost := rtr.NewDomain("[::1]:3000")
Middleware on Domains

Middleware can be added at the domain level to apply to all routes within that domain:

domain := rtr.NewDomain("admin.example.com")

// Add middleware that will run before all routes in this domain
domain.AddBeforeMiddlewares([]rtr.MiddlewareInterface{
    rtr.NewMiddleware(rtr.WithName("AdminAuth"), rtr.WithHandler(adminAuthMiddleware)),
    rtr.NewMiddleware(rtr.WithName("Logging"), rtr.WithHandler(loggingMiddleware)),
})

// Add middleware that will run after all routes in this domain
domain.AddAfterMiddlewares([]rtr.MiddlewareInterface{
    rtr.NewMiddleware(rtr.WithName("ResponseTime"), rtr.WithHandler(responseTimeMiddleware)),
})

Interfaces

RouterInterface

The main router interface that provides methods for managing routes and groups:

  • GetPrefix() / SetPrefix(): Manage router prefix
  • AddGroup() / AddGroups(): Add route groups
  • AddRoute() / AddRoutes(): Add individual routes
  • AddBeforeMiddlewares() / AddAfterMiddlewares(): Add middleware chains
  • ServeHTTP(): Handle HTTP requests
GroupInterface

Interface for managing route groups:

  • GetPrefix() / SetPrefix(): Manage group prefix
  • AddRoute() / AddRoutes(): Add routes to the group
  • AddGroup() / AddGroups(): Add nested groups
  • AddBeforeMiddlewares() / AddAfterMiddlewares(): Add group-level middleware
RouteInterface

Interface for configuring individual routes:

  • GetMethod() / SetMethod(): HTTP method configuration
  • GetPath() / SetPath(): URL path configuration
  • GetHandler() / SetHandler(): Route handler configuration
  • GetName() / SetName(): Route naming
  • AddBeforeMiddlewares() / AddAfterMiddlewares(): Route-specific middleware
Shortcut Methods

The package provides shortcut methods for common HTTP methods:

  • Get(path string, handler Handler) RouteInterface - Creates a GET route
  • Post(path string, handler Handler) RouteInterface - Creates a POST route
  • Put(path string, handler Handler) RouteInterface - Creates a PUT route
  • Delete(path string, handler Handler) RouteInterface - Creates a DELETE route

These methods automatically set the HTTP method, path, and handler, making route creation more concise.

Route Listing and Debugging

The router provides a built-in List() method for debugging and documentation purposes. This method displays the router's configuration in formatted tables, making it easy to visualize your routing structure.

Using the List Method
router := rtr.NewRouter()

// Add some routes and middleware
router.AddBeforeMiddlewares([]rtr.MiddlewareInterface{rtr.NewMiddleware(rtr.WithName("Logging"), rtr.WithHandler(loggingMiddleware))})
router.AddRoute(rtr.Get("/", homeHandler).SetName("Home"))

// Create a group
apiGroup := rtr.NewGroup().SetPrefix("/api")
apiGroup.AddRoute(rtr.Get("/users", usersHandler).SetName("List Users"))
router.AddGroup(apiGroup)

// Display the router configuration
router.List()
Output Format

The List() method displays:

  1. Global Middleware Table: Shows before and after middleware applied at the router level
  2. Domain Routes Tables: Shows routes organized by domain (if using domain-based routing)
  3. Direct Routes Table: Shows routes added directly to the router
  4. Group Routes Tables: Shows routes organized by groups with their prefixes
Example Output
+------------------------------------+
| GLOBAL BEFORE MIDDLEWARE LIST (TOTAL: 2) |
+---+--------------------------------+------+
| # | MIDDLEWARE NAME                | TYPE |
+---+--------------------------------+------+
| 1 | RecoveryMiddleware             | Before |
| 2 | LoggingMiddleware              | Before |
+---+--------------------------------+------+

+---------------------------------------------------------------+
| DIRECT ROUTES LIST (TOTAL: 1)                                |
+---+------------+--------+------------+---------------------+
| # | ROUTE PATH | METHOD | ROUTE NAME | MIDDLEWARE LIST     |
+---+------------+--------+------------+---------------------+
| 1 | /          | GET    | Home       | none                |
+---+------------+--------+------------+---------------------+

+---------------------------------------------------------------+
| GROUP ROUTES [/api] (TOTAL: 1)                               |
+---+------------+--------+------------+---------------------+
| # | ROUTE PATH | METHOD | ROUTE NAME | MIDDLEWARE LIST     |
+---+------------+--------+------------+---------------------+
| 1 | /api/users | GET    | List Users | none                |
+---+------------+--------+------------+---------------------+
Middleware Name Detection

The List method attempts to extract meaningful names from middleware functions using reflection:

  • Named functions: Shows the actual function name (e.g., RecoveryMiddleware)
  • Anonymous functions: Shows anonymous or attempts to extract from closure context
  • Method receivers: Shows the method name when middleware is defined on a struct
Use Cases
  • Development: Quickly verify your routing configuration
  • Debugging: Identify routing conflicts or missing routes
  • Documentation: Generate route documentation for your API
  • Testing: Validate that routes are configured as expected

Testing

The package includes comprehensive test coverage:

  • router_test.go: Core router functionality tests
  • router_integration_test.go: Integration tests
  • route_test.go: Route-specific tests
  • group_test.go: Group functionality tests
  • examples/basic/: Complete example with tests

Run tests using:

# From the root directory
go test .

# Or to run all tests including examples
go test ./...

Documentation

Index

Constants

View Source
const (
	StatusEnabled  = "enabled"
	StatusDisabled = "disabled"
)

Status constants for declarative configuration

View Source
const (
	TypeRoute      = "route"
	TypeGroup      = "group"
	TypeDomain     = "domain"
	TypeMiddleware = "middleware"
)

Type constants for declarative configuration

View Source
const (
	MethodGET     = "GET"
	MethodPOST    = "POST"
	MethodPUT     = "PUT"
	MethodPATCH   = "PATCH"
	MethodDELETE  = "DELETE"
	MethodHEAD    = "HEAD"
	MethodOPTIONS = "OPTIONS"
)

HTTP method constants for declarative configuration

View Source
const ExecutionSequenceKey contextKey = "rtr.execution.sequence"

ExecutionSequenceKey is used to track the execution sequence of middlewares in tests

View Source
const ParamsKey contextKey = "rtr.path.params"

ParamsKey is the key used to store path parameters in the request context Using a more specific key to avoid collisions with other packages ParamsKey is the key used to store path parameters in the request context Using a more specific key to avoid collisions with other packages

Variables

This section is empty.

Functions

func BuildMiddlewareChain added in v0.9.0

func BuildMiddlewareChain(handler http.Handler, middlewares []MiddlewareInterface) http.Handler

BuildMiddlewareChain builds a middleware chain from a single slice of middlewares. The middlewares are applied in order, with the first middleware in the slice being the outermost.

func BuildMiddlewareChainFromSlices added in v0.9.0

func BuildMiddlewareChainFromSlices(handler http.Handler, middlewareSlices ...[]MiddlewareInterface) http.Handler

BuildMiddlewareChainFromSlices builds a middleware chain from multiple slices of middlewares. The slices are processed in reverse order, with the first slice's middlewares being the outermost. Within each slice, middlewares are applied in reverse order to maintain the correct execution sequence.

func CSSResponse added in v0.4.0

func CSSResponse(w http.ResponseWriter, r *http.Request, body string)

CSSResponse responds with CSS content and sets the appropriate Content-Type header. It sets the Content-Type to "text/css".

func ExecuteMiddlewareChain added in v0.6.0

func ExecuteMiddlewareChain(middlewares []MiddlewareInterface, finalHandler http.Handler) http.Handler

ExecuteMiddlewareChain executes a chain of MiddlewareInterface in order. This is a helper function that applies all middleware in the slice to the final handler.

func GetMiddlewareName added in v0.4.0

func GetMiddlewareName(middleware StdMiddleware) string

GetMiddlewareName attempts to get a readable name for a middleware function

func GetParam added in v0.1.3

func GetParam(r *http.Request, name string) (string, bool)

GetParam retrieves a path parameter from the request context by name. Returns the parameter value and true if found, or an empty string and false otherwise.

func GetParams added in v0.1.3

func GetParams(r *http.Request) map[string]string

GetParams returns all path parameters as a map. Returns an empty map if no parameters exist.

func GetRouteMiddlewareNames added in v0.4.0

func GetRouteMiddlewareNames(route RouteInterface) []string

GetRouteMiddlewareNames gets middleware names for a route

func HTMLResponse added in v0.4.0

func HTMLResponse(w http.ResponseWriter, r *http.Request, body string)

HTMLResponse responds with HTML content and sets the appropriate Content-Type header. It sets the Content-Type to "text/html; charset=utf-8" if not already set.

func JSONResponse added in v0.4.0

func JSONResponse(w http.ResponseWriter, r *http.Request, body string)

JSONResponse responds with JSON content and sets the appropriate Content-Type header. It sets the Content-Type to "application/json".

func JSResponse added in v0.4.0

func JSResponse(w http.ResponseWriter, r *http.Request, body string)

JSResponse responds with JavaScript content and sets the appropriate Content-Type header. It sets the Content-Type to "application/javascript".

func MustGetParam added in v0.1.3

func MustGetParam(r *http.Request, name string) string

MustGetParam retrieves a path parameter from the request context by name. Panics if the parameter is not found. Use only when you're certain the parameter exists.

func TextResponse added in v0.4.0

func TextResponse(w http.ResponseWriter, r *http.Request, body string)

TextResponse responds with plain text content and sets the appropriate Content-Type header. It sets the Content-Type to "text/plain; charset=utf-8".

func XMLResponse added in v0.4.0

func XMLResponse(w http.ResponseWriter, r *http.Request, body string)

XMLResponse responds with XML content and sets the appropriate Content-Type header. It sets the Content-Type to "application/xml".

Types

type CSSHandler added in v0.4.0

type CSSHandler StringHandler

CSSHandler is a convenience shorthand handler that returns CSS content. Automatically sets Content-Type: "text/css" header. Returns a CSS string that will be wrapped with CSSResponse().

type Domain added in v0.3.0

type Domain struct {
	Status      string          `json:"status,omitempty"`
	Hosts       []string        `json:"hosts,omitempty"`
	Items       []ItemInterface `json:"items,omitempty"` // Can contain both Groups and Routes in sequence
	Middlewares []string        `json:"middlewares,omitempty"`
	Name        string          `json:"name,omitempty"`
}

Domain represents a domain-specific routing configuration

func (Domain) GetMiddlewares added in v0.6.0

func (d Domain) GetMiddlewares() []string

GetMiddlewares implements ItemInterface

func (Domain) GetName added in v0.6.0

func (d Domain) GetName() string

GetName implements ItemInterface

func (Domain) GetStatus added in v0.6.0

func (d Domain) GetStatus() string

GetStatus implements ItemInterface

func (Domain) MarshalJSON added in v0.7.0

func (d Domain) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Domain

func (*Domain) UnmarshalJSON added in v0.7.0

func (d *Domain) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Domain

type DomainInterface

type DomainInterface interface {
	// GetPatterns returns the domain patterns that this domain matches against
	GetPatterns() []string

	// SetPatterns sets the domain patterns for this domain and returns the domain for method chaining
	SetPatterns(patterns ...string) DomainInterface

	// AddRoute adds a route to this domain and returns the domain for method chaining
	AddRoute(route RouteInterface) DomainInterface

	// AddRoutes adds multiple routes to this domain and returns the domain for method chaining
	AddRoutes(routes []RouteInterface) DomainInterface

	// GetRoutes returns all routes that belong to this domain
	GetRoutes() []RouteInterface

	// AddGroup adds a group to this domain and returns the domain for method chaining
	AddGroup(group GroupInterface) DomainInterface

	// AddGroups adds multiple groups to this domain and returns the domain for method chaining
	AddGroups(groups []GroupInterface) DomainInterface

	// GetGroups returns all groups that belong to this domain
	GetGroups() []GroupInterface

	// AddBeforeMiddlewares adds middleware functions to be executed before any route handler in this domain
	// Returns the domain for method chaining
	AddBeforeMiddlewares(middleware []MiddlewareInterface) DomainInterface

	// GetBeforeMiddlewares returns all middleware functions that will be executed before any route handler in this domain
	GetBeforeMiddlewares() []MiddlewareInterface

	// AddAfterMiddlewares adds middleware functions to be executed after any route handler in this domain
	// Returns the domain for method chaining
	AddAfterMiddlewares(middleware []MiddlewareInterface) DomainInterface

	// GetAfterMiddlewares returns all middleware functions that will be executed after any route handler in this domain
	GetAfterMiddlewares() []MiddlewareInterface

	// Match checks if the given host matches any of this domain's patterns
	Match(host string) bool
}

DomainInterface defines the interface for a domain that can have routes and groups. A domain represents a collection of routes and groups that are only accessible when the request's Host header matches the domain's patterns.

func NewDomain

func NewDomain(patterns ...string) DomainInterface

NewDomain creates a new domain with the given patterns

type ErrorHandler added in v0.4.0

type ErrorHandler func(http.ResponseWriter, *http.Request) error

ErrorHandler is a convenience shorthand handler for error responses. Returns an error that will be handled appropriately. If the returned error is nil, it means no error occurred and the response is successful. Content-Type and status codes are left to specific extensions like 404ErrorHandler.

type Group added in v0.3.0

type Group struct {
	Status      string   `json:"status,omitempty"`
	Prefix      string   `json:"prefix,omitempty"`
	Routes      []Route  `json:"routes,omitempty"`
	Middlewares []string `json:"middlewares,omitempty"`
	Name        string   `json:"name,omitempty"`
}

Group represents a group of routes

func (Group) GetMiddlewares added in v0.6.0

func (g Group) GetMiddlewares() []string

GetMiddlewares implements ItemInterface

func (Group) GetName added in v0.6.0

func (g Group) GetName() string

GetName implements ItemInterface

func (Group) GetStatus added in v0.6.0

func (g Group) GetStatus() string

GetStatus implements ItemInterface

func (Group) MarshalJSON added in v0.7.0

func (g Group) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Group

func (*Group) UnmarshalJSON added in v0.7.0

func (g *Group) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Group

type GroupInterface

type GroupInterface interface {
	// GetPrefix returns the URL path prefix associated with this group.
	GetPrefix() string
	// SetPrefix sets the URL path prefix for this group and returns the group for method chaining.
	SetPrefix(prefix string) GroupInterface

	// AddRoute adds a single route to this group and returns the group for method chaining.
	AddRoute(route RouteInterface) GroupInterface
	// AddRoutes adds multiple routes to this group and returns the group for method chaining.
	AddRoutes(routes []RouteInterface) GroupInterface
	// GetRoutes returns all routes that belong to this group.
	GetRoutes() []RouteInterface

	// AddGroup adds a single nested group to this group and returns the group for method chaining.
	AddGroup(group GroupInterface) GroupInterface
	// AddGroups adds multiple nested groups to this group and returns the group for method chaining.
	AddGroups(groups []GroupInterface) GroupInterface
	// GetGroups returns all nested groups that belong to this group.
	GetGroups() []GroupInterface

	// AddBeforeMiddlewares adds middleware to be executed before any route handler in this group.
	// Returns the group for method chaining.
	AddBeforeMiddlewares(middleware []MiddlewareInterface) GroupInterface
	// GetBeforeMiddlewares returns all middleware that will be executed before any route handler in this group.
	GetBeforeMiddlewares() []MiddlewareInterface

	// AddAfterMiddlewares adds middleware to be executed after any route handler in this group
	// Returns the group for method chaining
	AddAfterMiddlewares(middleware []MiddlewareInterface) GroupInterface

	// GetAfterMiddlewares returns all middleware that will be executed after any route handler in this group
	GetAfterMiddlewares() []MiddlewareInterface
}

GroupInterface defines the interface for a group of routes. A group represents a collection of routes that share common properties such as a URL prefix and middleware. Groups can also be nested to create hierarchical route structures.

func NewGroup

func NewGroup() GroupInterface

NewGroup creates and returns a new GroupInterface implementation. This is used to create a new route group that can be added to a router.

type HTMLHandler added in v0.4.0

type HTMLHandler StringHandler

HTMLHandler is a convenience shorthand handler that returns HTML content. Automatically sets Content-Type: "text/html; charset=utf-8" header. Returns an HTML string that will be wrapped with HTMLResponse().

type HandlerRegistry added in v0.6.0

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

HandlerRegistry maps string names to actual functions

func NewHandlerRegistry added in v0.6.0

func NewHandlerRegistry() *HandlerRegistry

NewHandlerRegistry creates a new handler registry

func (*HandlerRegistry) AddMiddleware added in v0.6.0

func (r *HandlerRegistry) AddMiddleware(middleware MiddlewareInterface)

AddMiddleware adds middleware to the registry

func (*HandlerRegistry) AddRoute added in v0.6.0

func (r *HandlerRegistry) AddRoute(route RouteInterface)

AddRoute adds a route to the registry

func (*HandlerRegistry) FindMiddleware added in v0.6.0

func (r *HandlerRegistry) FindMiddleware(name string) MiddlewareInterface

FindMiddleware finds middleware by name

func (*HandlerRegistry) FindRoute added in v0.6.0

func (r *HandlerRegistry) FindRoute(name string) RouteInterface

FindRoute finds a route by name

func (*HandlerRegistry) RemoveMiddleware added in v0.6.0

func (r *HandlerRegistry) RemoveMiddleware(name string)

RemoveMiddleware removes a middleware factory from the registry

func (*HandlerRegistry) RemoveRoute added in v0.6.0

func (r *HandlerRegistry) RemoveRoute(name string)

RemoveRoute removes a route handler from the registry

type ItemInterface added in v0.6.0

type ItemInterface interface {
	NameInterface
	StatusInterface
	GetMiddlewares() []string
}

ItemInterface represents a common interface for groups and routes

type JSHandler added in v0.4.0

type JSHandler StringHandler

JSHandler is a convenience shorthand handler that returns JavaScript content. Automatically sets Content-Type: "application/javascript" header. Returns a JavaScript string that will be wrapped with JSResponse().

type JSONHandler added in v0.4.0

type JSONHandler StringHandler

JSONHandler is a convenience shorthand handler that returns JSON content. Automatically sets Content-Type: "application/json" header. Returns a JSON string that will be wrapped with JSONResponse().

type Middleware

type Middleware struct {
	Name    string
	Handler string
	Config  map[string]any
}

Middleware represents middleware configuration

type MiddlewareInfo added in v0.2.0

type MiddlewareInfo struct {
	Name string
	Func StdMiddleware
}

MiddlewareInfo represents middleware information for display purposes

type MiddlewareInterface added in v0.6.0

type MiddlewareInterface interface {
	// GetName returns the name identifier associated with this middleware.
	// Returns the string name of the middleware, which may be empty for anonymous middleware.
	GetName() string
	// SetName sets the name identifier for this middleware and returns the middleware for method chaining.
	// The name parameter can be used for middleware identification and debugging.
	SetName(name string) MiddlewareInterface

	// GetHandler returns the underlying middleware function.
	// Returns the StdMiddleware function that will be executed.
	GetHandler() StdMiddleware
	// SetHandler sets the middleware function and returns the middleware for method chaining.
	// The handler parameter should be a valid StdMiddleware function.
	SetHandler(handler StdMiddleware) MiddlewareInterface

	// Execute applies the middleware to the given handler.
	// This is equivalent to calling GetHandler()(next).
	Execute(next http.Handler) http.Handler
}

MiddlewareInterface defines the interface for named middleware. It provides a way to associate a name with middleware for better debugging and documentation.

func AddMiddlewaresToInterfaces added in v0.6.0

func AddMiddlewaresToInterfaces(interfaces []MiddlewareInterface, middlewares []StdMiddleware) []MiddlewareInterface

AddMiddlewaresToInterfaces converts and adds StdMiddleware functions to a MiddlewareInterface slice

func MiddlewareFromFunction added in v0.6.0

func MiddlewareFromFunction(handler StdMiddleware) MiddlewareInterface

MiddlewareFromFunction converts a StdMiddleware function to a MiddlewareInterface. This is a convenience function for backward compatibility.

func MiddlewaresToInterfaces added in v0.6.0

func MiddlewaresToInterfaces(middlewares []StdMiddleware) []MiddlewareInterface

MiddlewaresToInterfaces converts a slice of StdMiddleware functions to MiddlewareInterface slice. This is useful for migrating existing code that uses []StdMiddleware to []MiddlewareInterface.

func NewAnonymousMiddleware added in v0.6.0

func NewAnonymousMiddleware(handler StdMiddleware) MiddlewareInterface

NewAnonymousMiddleware creates a new middleware with the given handler. This is a convenience function that's equivalent to NewMiddleware(WithHandler(handler)). It's maintained for backward compatibility with existing code.

func NewMiddleware added in v0.6.0

func NewMiddleware(opts ...MiddlewareOption) MiddlewareInterface

NewMiddleware creates a new middleware with the provided options. Example: NewMiddleware(WithName("auth"), WithHandler(myAuthHandler))

type MiddlewareOption added in v0.7.0

type MiddlewareOption func(*middlewareImpl)

MiddlewareOption defines a function type that can configure a middleware

func WithHandler added in v0.7.0

func WithHandler(handler StdMiddleware) MiddlewareOption

WithHandler returns a MiddlewareOption that sets the handler function of the middleware

func WithName added in v0.7.0

func WithName(name string) MiddlewareOption

WithName returns a MiddlewareOption that sets the name of the middleware

type NameInterface added in v0.6.0

type NameInterface interface {
	GetName() string
}

type Route added in v0.6.0

type Route struct {
	Status       string   `json:"status,omitempty"`
	Path         string   `json:"path,omitempty"`
	Method       string   `json:"method,omitempty"`
	Handler      string   `json:"handler,omitempty"`      // Standard HTTP handler reference
	HTMLHandler  string   `json:"htmlHandler,omitempty"`  // HTML handler reference
	JSONHandler  string   `json:"jsonHandler,omitempty"`  // JSON handler reference
	CSSHandler   string   `json:"cssHandler,omitempty"`   // CSS handler reference
	XMLHandler   string   `json:"xmlHandler,omitempty"`   // XML handler reference
	TextHandler  string   `json:"textHandler,omitempty"`  // Text handler reference
	JSHandler    string   `json:"jsHandler,omitempty"`    // JavaScript handler reference
	ErrorHandler string   `json:"errorHandler,omitempty"` // Error handler reference
	Name         string   `json:"name,omitempty"`
	Middlewares  []string `json:"middlewares,omitempty"`
}

Route represents a single route configuration

func (Route) GetMiddlewares added in v0.6.0

func (r Route) GetMiddlewares() []string

GetMiddlewares implements ItemInterface

func (Route) GetName added in v0.6.0

func (r Route) GetName() string

GetName implements ItemInterface

func (Route) GetStatus added in v0.6.0

func (r Route) GetStatus() string

GetStatus implements ItemInterface

func (Route) MarshalJSON added in v0.7.0

func (r Route) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Route

func (*Route) UnmarshalJSON added in v0.7.0

func (r *Route) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Route

type RouteInterface

type RouteInterface interface {
	// GetMethod returns the HTTP method associated with this route.
	GetMethod() string
	// SetMethod sets the HTTP method for this route and returns the route for method chaining.
	SetMethod(method string) RouteInterface

	// GetPath returns the URL path pattern associated with this route.
	GetPath() string
	// SetPath sets the URL path pattern for this route and returns the route for method chaining.
	SetPath(path string) RouteInterface

	// GetHandler returns the handler function associated with this route.
	GetHandler() StdHandler
	// SetHandler sets the handler function for this route and returns the route for method chaining.
	SetHandler(handler StdHandler) RouteInterface

	// GetStringHandler returns the string handler function associated with this route.
	GetStringHandler() StringHandler
	// SetStringHandler sets the string handler function for this route and returns the route for method chaining.
	SetStringHandler(handler StringHandler) RouteInterface

	// GetHTMLHandler returns the HTML handler function associated with this route.
	GetHTMLHandler() HTMLHandler
	// SetHTMLHandler sets the HTML handler function for this route and returns the route for method chaining.
	SetHTMLHandler(handler HTMLHandler) RouteInterface

	// GetJSONHandler returns the JSON handler function associated with this route.
	GetJSONHandler() JSONHandler
	// SetJSONHandler sets the JSON handler function for this route and returns the route for method chaining.
	SetJSONHandler(handler JSONHandler) RouteInterface

	// GetCSSHandler returns the CSS handler function associated with this route.
	GetCSSHandler() CSSHandler
	// SetCSSHandler sets the CSS handler function for this route and returns the route for method chaining.
	SetCSSHandler(handler CSSHandler) RouteInterface

	// GetXMLHandler returns the XML handler function associated with this route.
	GetXMLHandler() XMLHandler
	// SetXMLHandler sets the XML handler function for this route and returns the route for method chaining.
	SetXMLHandler(handler XMLHandler) RouteInterface

	// GetTextHandler returns the text handler function associated with this route.
	GetTextHandler() TextHandler
	// SetTextHandler sets the text handler function for this route and returns the route for method chaining.
	SetTextHandler(handler TextHandler) RouteInterface

	// GetJSHandler returns the JavaScript handler function associated with this route.
	GetJSHandler() JSHandler
	// SetJSHandler sets the JavaScript handler function for this route and returns the route for method chaining.
	SetJSHandler(handler JSHandler) RouteInterface

	// GetErrorHandler returns the error handler function associated with this route.
	GetErrorHandler() ErrorHandler
	// SetErrorHandler sets the error handler function for this route and returns the route for method chaining.
	SetErrorHandler(handler ErrorHandler) RouteInterface

	// GetName returns the name identifier associated with this route.
	GetName() string
	// SetName sets the name identifier for this route and returns the route for method chaining.
	SetName(name string) RouteInterface

	// AddBeforeMiddlewares adds middleware functions to be executed before the route handler.
	// Returns the route for method chaining.
	AddBeforeMiddlewares(middleware []MiddlewareInterface) RouteInterface
	// GetBeforeMiddlewares returns all middleware functions that will be executed before the route handler.
	GetBeforeMiddlewares() []MiddlewareInterface

	// AddAfterMiddlewares adds middleware functions to be executed after the route handler.
	// Returns the route for method chaining.
	AddAfterMiddlewares(middleware []MiddlewareInterface) RouteInterface
	// GetAfterMiddlewares returns all middleware functions that will be executed after the route handler.
	GetAfterMiddlewares() []MiddlewareInterface
}

RouteInterface defines the interface for a single route definition. A route represents a mapping between an HTTP method, a URL path pattern, and a handler function. Routes can also have associated middleware that will be executed before or after the handler.

func Delete

func Delete(path string, handler StdHandler) RouteInterface

Delete creates a new DELETE route with the given path and handler It is a shortcut method that combines setting the method to DELETE, path, and handler.

func Get

func Get(path string, handler StdHandler) RouteInterface

Get creates a new GET route with the given path and handler It is a shortcut method that combines setting the method to GET, path, and handler.

func GetCSS added in v0.4.0

func GetCSS(path string, handler CSSHandler) RouteInterface

GetCSS creates a new GET route with the given path and CSS handler It is a shortcut method that combines setting the method to GET, path, and CSS handler.

func GetHTML added in v0.4.0

func GetHTML(path string, handler HTMLHandler) RouteInterface

GetHTML creates a new GET route with the given path and HTML handler It is a shortcut method that combines setting the method to GET, path, and HTML handler.

func GetJSON added in v0.4.0

func GetJSON(path string, handler JSONHandler) RouteInterface

GetJSON creates a new GET route with the given path and JSON handler It is a shortcut method that combines setting the method to GET, path, and JSON handler.

func GetText added in v0.4.0

func GetText(path string, handler TextHandler) RouteInterface

GetText creates a new GET route with the given path and text handler It is a shortcut method that combines setting the method to GET, path, and text handler.

func GetXML added in v0.4.0

func GetXML(path string, handler XMLHandler) RouteInterface

GetXML creates a new GET route with the given path and XML handler It is a shortcut method that combines setting the method to GET, path, and XML handler.

func NewRoute

func NewRoute() RouteInterface

This is used to create a new route that can be added to a router or group.

func Post

func Post(path string, handler StdHandler) RouteInterface

Post creates a new POST route with the given path and handler It is a shortcut method that combines setting the method to POST, path, and handler.

func PostHTML added in v0.4.0

func PostHTML(path string, handler HTMLHandler) RouteInterface

PostHTML creates a new POST route with the given path and HTML handler It is a shortcut method that combines setting the method to POST, path, and HTML handler.

func PostJSON added in v0.4.0

func PostJSON(path string, handler JSONHandler) RouteInterface

PostJSON creates a new POST route with the given path and JSON handler It is a shortcut method that combines setting the method to POST, path, and JSON handler.

func Put

func Put(path string, handler StdHandler) RouteInterface

Put creates a new PUT route with the given path and handler It is a shortcut method that combines setting the method to PUT, path, and handler.

type RouterInterface

type RouterInterface interface {
	// GetPrefix returns the URL path prefix associated with this router.
	GetPrefix() string
	// SetPrefix sets the URL path prefix for this router and returns the router for method chaining.
	// The prefix will be prepended to all routes in this router.
	SetPrefix(prefix string) RouterInterface

	// AddGroup adds a single group to this router and returns the router for method chaining.
	// The group's prefix will be combined with the router's prefix for all routes in the group.
	AddGroup(group GroupInterface) RouterInterface
	// AddGroups adds multiple groups to this router and returns the router for method chaining.
	// Each group's prefix will be combined with the router's prefix for all routes in the group.
	AddGroups(groups []GroupInterface) RouterInterface
	// GetGroups returns all groups that belong to this router.
	// Returns a slice of GroupInterface implementations.
	GetGroups() []GroupInterface

	// AddRoute adds a single route to this router and returns the router for method chaining.
	// The route's path will be prefixed with the router's prefix.
	AddRoute(route RouteInterface) RouterInterface
	// AddRoutes adds multiple routes to this router and returns the router for method chaining.
	// Each route's path will be prefixed with the router's prefix.
	AddRoutes(routes []RouteInterface) RouterInterface
	// GetRoutes returns all routes that belong to this router.
	// Returns a slice of RouteInterface implementations.
	GetRoutes() []RouteInterface

	// AddBeforeMiddlewares adds middleware to be executed before any route handler.
	// The middleware will be executed in the order they are added.
	// Returns the router for method chaining.
	AddBeforeMiddlewares(middleware []MiddlewareInterface) RouterInterface
	// GetBeforeMiddlewares returns all middleware that will be executed before any route handler.
	// Returns a slice of MiddlewareInterface.
	GetBeforeMiddlewares() []MiddlewareInterface

	// AddAfterMiddlewares adds middleware to be executed after any route handler.
	// The middleware will be executed in reverse order of how they were added.
	// Returns the router for method chaining.
	AddAfterMiddlewares(middleware []MiddlewareInterface) RouterInterface
	// GetAfterMiddlewares returns all middleware that will be executed after any route handler.
	// Returns a slice of MiddlewareInterface.
	GetAfterMiddlewares() []MiddlewareInterface

	// AddDomain adds a domain to this router and returns the router for method chaining
	AddDomain(domain DomainInterface) RouterInterface

	// AddDomains adds multiple domains to this router and returns the router for method chaining
	AddDomains(domains []DomainInterface) RouterInterface

	// GetDomains returns all domains that belong to this router
	GetDomains() []DomainInterface

	// List displays the router's configuration in formatted tables for debugging and documentation
	// Shows global middleware, domains, direct routes, and route groups
	List()

	// ServeHTTP implements the http.Handler interface.
	// It matches the incoming request to the appropriate route and executes the handler.
	ServeHTTP(w http.ResponseWriter, r *http.Request)
}

RouterInterface defines the interface for a router that can handle HTTP requests. A router is responsible for matching incoming HTTP requests to the appropriate route handler and executing any associated middleware.

func NewRouter

func NewRouter() RouterInterface

NewRouter creates and returns a new RouterInterface implementation. This is the main entry point for creating a new router. The router starts with no default middlewares - users should add middlewares as needed.

type StatusInterface added in v0.6.0

type StatusInterface interface {
	GetStatus() string
}

type StdHandler added in v0.6.0

type StdHandler func(http.ResponseWriter, *http.Request)

StdHandler defines the function signature for standard HTTP request handlers. This is the standard Go HTTP handler pattern, distinct from any potential named handler interfaces.

func ErrorHandlerToHandler added in v0.4.0

func ErrorHandlerToHandler(handler ErrorHandler) StdHandler

ErrorHandlerToHandler converts an ErrorHandler to a standard Handler. If the error handler returns an error, it writes the error message to the response. If the error handler returns nil, it does nothing.

Parameters:

  • handler: The error handler function to convert.

Returns:

  • A standard Handler function that writes the error message to the response if an error is returned.

func ToStdHandler added in v0.6.0

func ToStdHandler(handler StringHandler) StdHandler

ToStdHandler converts any string-returning handler to a standard Handler. It simply writes the returned string to the response without setting any headers. The string handler is responsible for setting any headers it needs.

Parameters:

  • handler: The string handler function to convert.

Returns:

  • A standard Handler function that writes the returned string to the response.

type StdMiddleware added in v0.6.0

type StdMiddleware func(http.Handler) http.Handler

StdMiddleware represents a standard middleware function. It is a function type that takes an http.Handler and returns an http.Handler. StdMiddleware functions can be used to process requests before or after they reach the main handler. This is the standard Go HTTP middleware pattern, distinct from MiddlewareInterface which provides named middleware.

func InterfacesToMiddlewares added in v0.6.0

func InterfacesToMiddlewares(interfaces []MiddlewareInterface) []StdMiddleware

InterfacesToMiddlewares converts a slice of MiddlewareInterface to StdMiddleware functions. This is useful for backward compatibility when you need to work with the underlying functions.

type StringHandler added in v0.4.0

type StringHandler func(http.ResponseWriter, *http.Request) string

StringHandler is a convenience shorthand handler for simple string responses. It returns a string that will be written directly to the response without setting any headers. The handler is responsible for setting any headers it needs.

type TextHandler added in v0.4.0

type TextHandler StringHandler

TextHandler is a convenience shorthand handler that returns plain text content. Automatically sets Content-Type: "text/plain; charset=utf-8" header. Returns a plain text string that will be wrapped with TextResponse().

type XMLHandler added in v0.4.0

type XMLHandler StringHandler

XMLHandler is a convenience shorthand handler that returns XML content. Automatically sets Content-Type: "application/xml" header. Returns an XML string that will be wrapped with XMLResponse().

Directories

Path Synopsis
examples
basic command
declarative command
domain command
handlers command
middleware command
path-parameters command

Jump to

Keyboard shortcuts

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