rtr

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2025 License: AGPL-3.0 Imports: 9 Imported by: 0

README

HTTP Router Package

A flexible and feature-rich HTTP router implementation for Go applications that supports route grouping, middleware chains, and nested routing structures.

Tests Status Go Report Card PkgGoDev License

Features

  • Route Management: Define and manage HTTP routes with support for all standard HTTP methods using exact path matching
  • Route Groups: Group related routes with shared prefixes and middleware
  • Middleware Support:
    • Pre-route (before) middleware
    • Post-route (after) middleware
    • Support at router, 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

Middleware

Built-in Middleware
Recovery Middleware

The router includes a built-in recovery middleware that catches panics in your handlers and returns a 500 Internal Server Error response instead of crashing the server. This middleware is added by default when you create a new router with NewRouter().

// This is automatically added when you create a new router
router := router.NewRouter()

// But you can also add it manually if needed
router.AddBeforeMiddlewares([]router.Middleware{router.RecoveryMiddleware})
Custom Middleware

You can create your own middleware by implementing the Middleware type:

func myMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Do something before the handler runs
        log.Println("Before handler")
        
        // Call the next handler
        next.ServeHTTP(w, r)
        
        // Do something after the handler runs
        log.Println("After handler")
    })
}

// Add it to your router
router.AddBeforeMiddlewares([]router.Middleware{myMiddleware})

Core Components

Router

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

router := router.NewRouter()
Routes

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

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

// Using method chaining
route := router.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.

Handler Priority

When multiple handlers are set on a route, they are prioritized in the following order:

  1. Handler - Standard HTTP handler (highest priority)
  2. StringHandler - Generic string handler
  3. HTMLHandler - HTML content handler
  4. JSONHandler - JSON content handler
  5. CSSHandler - CSS stylesheet handler
  6. XMLHandler - XML content handler
  7. TextHandler - Plain text handler
  8. JSHandler - JavaScript content handler
  9. ErrorHandler - Generic error-returning handler (lowest priority)
Standard Handler

The traditional HTTP handler with full control over the response:

r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/users").
    SetHandler(func(w http.ResponseWriter, req *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(`{"users": []}`))
    }))
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 := router.NewGroup()
    .SetPrefix("/api")
    .AddRoute(route)

Usage Examples

Basic Router Setup
r := router.NewRouter()

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

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

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

// Add the group to the router
r.AddGroup(apiGroup)
Adding Middleware
// Router-level middleware
r.AddBeforeMiddlewares([]router.Middleware{
    loggingMiddleware,
    authenticationMiddleware,
})

// Group-level middleware
apiGroup.AddBeforeMiddlewares([]router.Middleware{
    apiKeyMiddleware,
})

// Route-level middleware
route.AddBeforeMiddlewares([]router.Middleware{
    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(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))
Wildcard/Catch-all Routes

Use * to match all remaining path segments:

// Matches /static/js/main.js, /static/css/style.css, etc.
r.AddRoute(rtr.NewRoute().
    SetMethod("GET").
    SetPath("/static/*filepath").
    SetHandler(serveStaticFile))
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
  • The wildcard parameter 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 := router.NewDomain("example.com")

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

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

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

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

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

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

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

// Add the domain to the router
router.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 := router.NewDomain("example.com")  // Matches example.com, example.com:8080, example.com:3000, etc.
    
  • Exact port: Requires exact port match

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

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

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

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

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

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

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

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

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

// Add middleware that will run before all routes in this domain
domain.AddBeforeMiddlewares([]router.Middleware{
    adminAuthMiddleware,
    loggingMiddleware,
})

// Add middleware that will run after all routes in this domain
domain.AddAfterMiddlewares([]router.Middleware{
    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.Middleware{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 (
	// 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 contextKey = "rtr.path.params"
)

Context key for storing path parameters in the request context

Variables

This section is empty.

Functions

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 GetMiddlewareName added in v0.4.0

func GetMiddlewareName(middleware Middleware) 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 RecoveryMiddleware

func RecoveryMiddleware(next http.Handler) http.Handler

RecoveryMiddleware creates a new middleware that recovers from panics. It logs the panic details and returns a 500 Internal Server Error response. This should typically be added as one of the first middlewares in the chain.

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 DomainConfig added in v0.3.0

type DomainConfig struct {
	Name             string                 `json:"name,omitempty"`
	Patterns         []string               `json:"patterns"`
	Routes           []RouteConfig          `json:"routes,omitempty"`
	Groups           []GroupConfig          `json:"groups,omitempty"`
	BeforeMiddleware []Middleware           `json:"-"`
	AfterMiddleware  []Middleware           `json:"-"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

DomainConfig represents a declarative domain configuration

func Domain added in v0.3.0

func Domain(patterns []string, items ...interface{}) DomainConfig

Domain creates a domain configuration

func (*DomainConfig) AddAfterMiddlewares added in v0.5.0

func (d *DomainConfig) AddAfterMiddlewares(middleware []Middleware) DomainInterface

AddAfterMiddlewares adds middleware functions to be executed after any route handler in this domain

func (*DomainConfig) AddBeforeMiddlewares added in v0.5.0

func (d *DomainConfig) AddBeforeMiddlewares(middleware []Middleware) DomainInterface

AddBeforeMiddlewares adds middleware functions to be executed before any route handler in this domain

func (*DomainConfig) AddGroup added in v0.5.0

func (d *DomainConfig) AddGroup(group GroupInterface) DomainInterface

AddGroup adds a group to this domain and returns the domain for method chaining

func (*DomainConfig) AddGroups added in v0.5.0

func (d *DomainConfig) AddGroups(groups []GroupInterface) DomainInterface

AddGroups adds multiple groups to this domain and returns the domain for method chaining

func (*DomainConfig) AddRoute added in v0.5.0

func (d *DomainConfig) AddRoute(route RouteInterface) DomainInterface

AddRoute adds a route to this domain and returns the domain for method chaining

func (*DomainConfig) AddRoutes added in v0.5.0

func (d *DomainConfig) AddRoutes(routes []RouteInterface) DomainInterface

AddRoutes adds multiple routes to this domain and returns the domain for method chaining

func (*DomainConfig) GetAfterMiddlewares added in v0.5.0

func (d *DomainConfig) GetAfterMiddlewares() []Middleware

GetAfterMiddlewares returns all middleware functions that will be executed after any route handler in this domain

func (*DomainConfig) GetBeforeMiddlewares added in v0.5.0

func (d *DomainConfig) GetBeforeMiddlewares() []Middleware

GetBeforeMiddlewares returns all middleware functions that will be executed before any route handler in this domain

func (*DomainConfig) GetGroups added in v0.5.0

func (d *DomainConfig) GetGroups() []GroupInterface

GetGroups returns all groups that belong to this domain

func (*DomainConfig) GetPatterns added in v0.5.0

func (d *DomainConfig) GetPatterns() []string

GetPatterns returns the domain patterns that this domain matches against

func (*DomainConfig) GetRoutes added in v0.5.0

func (d *DomainConfig) GetRoutes() []RouteInterface

GetRoutes returns all routes that belong to this domain

func (*DomainConfig) Match added in v0.5.0

func (d *DomainConfig) Match(host string) bool

Match checks if the given host matches any of this domain's patterns

func (*DomainConfig) SetPatterns added in v0.5.0

func (d *DomainConfig) SetPatterns(patterns ...string) DomainInterface

SetPatterns sets the domain patterns for this domain and returns the domain for method chaining

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 []Middleware) DomainInterface

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

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

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

	// 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 GroupConfig added in v0.3.0

type GroupConfig struct {
	Name             string                 `json:"name,omitempty"`
	Prefix           string                 `json:"prefix"`
	Routes           []RouteConfig          `json:"routes,omitempty"`
	Groups           []GroupConfig          `json:"groups,omitempty"`
	BeforeMiddleware []Middleware           `json:"-"`
	AfterMiddleware  []Middleware           `json:"-"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

GroupConfig represents a declarative group configuration

func Group added in v0.3.0

func Group(prefix string, items ...interface{}) GroupConfig

Group creates a group configuration

func (*GroupConfig) AddAfterMiddlewares added in v0.5.0

func (g *GroupConfig) AddAfterMiddlewares(middleware []Middleware) GroupInterface

AddAfterMiddlewares adds middleware functions to be executed after any route handler in this group.

func (*GroupConfig) AddBeforeMiddlewares added in v0.5.0

func (g *GroupConfig) AddBeforeMiddlewares(middleware []Middleware) GroupInterface

AddBeforeMiddlewares adds middleware functions to be executed before any route handler in this group.

func (*GroupConfig) AddGroup added in v0.5.0

func (g *GroupConfig) AddGroup(group GroupInterface) GroupInterface

AddGroup adds a single nested group to this group and returns the group for method chaining.

func (*GroupConfig) AddGroups added in v0.5.0

func (g *GroupConfig) AddGroups(groups []GroupInterface) GroupInterface

AddGroups adds multiple nested groups to this group and returns the group for method chaining.

func (*GroupConfig) AddRoute added in v0.5.0

func (g *GroupConfig) AddRoute(route RouteInterface) GroupInterface

AddRoute adds a single route to this group and returns the group for method chaining.

func (*GroupConfig) AddRoutes added in v0.5.0

func (g *GroupConfig) AddRoutes(routes []RouteInterface) GroupInterface

AddRoutes adds multiple routes to this group and returns the group for method chaining.

func (*GroupConfig) GetAfterMiddlewares added in v0.5.0

func (g *GroupConfig) GetAfterMiddlewares() []Middleware

GetAfterMiddlewares returns all middleware functions that will be executed after any route handler in this group.

func (*GroupConfig) GetBeforeMiddlewares added in v0.5.0

func (g *GroupConfig) GetBeforeMiddlewares() []Middleware

GetBeforeMiddlewares returns all middleware functions that will be executed before any route handler in this group.

func (*GroupConfig) GetGroups added in v0.5.0

func (g *GroupConfig) GetGroups() []GroupInterface

GetGroups returns all nested groups that belong to this group.

func (*GroupConfig) GetPrefix added in v0.5.0

func (g *GroupConfig) GetPrefix() string

GetPrefix returns the URL path prefix associated with this group.

func (*GroupConfig) GetRoutes added in v0.5.0

func (g *GroupConfig) GetRoutes() []RouteInterface

GetRoutes returns all routes that belong to this group.

func (*GroupConfig) SetPrefix added in v0.5.0

func (g *GroupConfig) SetPrefix(prefix string) GroupInterface

SetPrefix sets the URL path prefix for this group and returns the group for method chaining.

func (GroupConfig) WithAfterMiddleware added in v0.3.0

func (g GroupConfig) WithAfterMiddleware(middleware ...Middleware) GroupConfig

WithAfterMiddleware adds after middleware to a group configuration

func (GroupConfig) WithBeforeMiddleware added in v0.3.0

func (g GroupConfig) WithBeforeMiddleware(middleware ...Middleware) GroupConfig

WithBeforeMiddleware adds before middleware to a group configuration

func (GroupConfig) WithName added in v0.3.0

func (g GroupConfig) WithName(name string) GroupConfig

WithName adds a name to a group configuration

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 functions to be executed before any route handler in this group.
	// Returns the group for method chaining.
	AddBeforeMiddlewares(middleware []Middleware) GroupInterface
	// GetBeforeMiddlewares returns all middleware functions that will be executed before any route handler in this group.
	GetBeforeMiddlewares() []Middleware

	// AddAfterMiddlewares adds middleware functions to be executed after any route handler in this group.
	// Returns the group for method chaining.
	AddAfterMiddlewares(middleware []Middleware) GroupInterface
	// GetAfterMiddlewares returns all middleware functions that will be executed after any route handler in this group.
	GetAfterMiddlewares() []Middleware
}

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 Handler

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

Handler defines the function signature for HTTP request handlers.

func ErrorHandlerToHandler added in v0.4.0

func ErrorHandlerToHandler(handler ErrorHandler) Handler

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 ToHandler added in v0.4.0

func ToHandler(handler StringHandler) Handler

ToHandler 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 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 func(http.Handler) http.Handler

Middleware represents a middleware function. It is a function type that takes an http.Handler and returns an http.Handler. Middleware functions can be used to process requests before or after they reach the main handler.

func DefaultMiddlewares

func DefaultMiddlewares() []Middleware

DefaultMiddlewares returns a slice of default middlewares that should be used with the router. Currently, it only includes the RecoveryMiddleware.

type MiddlewareInfo added in v0.2.0

type MiddlewareInfo struct {
	Name string
	Func Middleware
}

MiddlewareInfo represents middleware information for display purposes

type RouteConfig added in v0.3.0

type RouteConfig struct {
	Name             string                 `json:"name,omitempty"`
	Method           string                 `json:"method,omitempty"`
	Path             string                 `json:"path"`
	Handler          Handler                `json:"-"`
	ErrorHandler     ErrorHandler           `json:"-"`
	HTMLHandler      HTMLHandler            `json:"-"`
	JSONHandler      JSONHandler            `json:"-"`
	CSSHandler       CSSHandler             `json:"-"`
	XMLHandler       XMLHandler             `json:"-"`
	TextHandler      TextHandler            `json:"-"`
	BeforeMiddleware []Middleware           `json:"-"`
	AfterMiddleware  []Middleware           `json:"-"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

RouteConfig represents a declarative route configuration

func DELETE added in v0.3.0

func DELETE(path string, handler Handler) RouteConfig

DELETE creates a DELETE route configuration

func GET added in v0.3.0

func GET(path string, handler Handler) RouteConfig

GET creates a GET route configuration

func OPTIONS added in v0.3.0

func OPTIONS(path string, handler Handler) RouteConfig

OPTIONS creates an OPTIONS route configuration

func PATCH added in v0.3.0

func PATCH(path string, handler Handler) RouteConfig

PATCH creates a PATCH route configuration

func POST added in v0.3.0

func POST(path string, handler Handler) RouteConfig

POST creates a POST route configuration

func PUT added in v0.3.0

func PUT(path string, handler Handler) RouteConfig

PUT creates a PUT route configuration

func (*RouteConfig) AddAfterMiddlewares added in v0.5.0

func (r *RouteConfig) AddAfterMiddlewares(middleware []Middleware) RouteInterface

AddAfterMiddlewares adds middleware functions to be executed after the route handler.

func (*RouteConfig) AddBeforeMiddlewares added in v0.5.0

func (r *RouteConfig) AddBeforeMiddlewares(middleware []Middleware) RouteInterface

AddBeforeMiddlewares adds middleware functions to be executed before the route handler.

func (*RouteConfig) GetAfterMiddlewares added in v0.5.0

func (r *RouteConfig) GetAfterMiddlewares() []Middleware

GetAfterMiddlewares returns all middleware functions that will be executed after the route handler.

func (*RouteConfig) GetBeforeMiddlewares added in v0.5.0

func (r *RouteConfig) GetBeforeMiddlewares() []Middleware

GetBeforeMiddlewares returns all middleware functions that will be executed before the route handler.

func (*RouteConfig) GetCSSHandler added in v0.5.0

func (r *RouteConfig) GetCSSHandler() CSSHandler

GetCSSHandler returns the CSS handler function associated with this route.

func (*RouteConfig) GetErrorHandler added in v0.5.0

func (r *RouteConfig) GetErrorHandler() ErrorHandler

GetErrorHandler returns the error handler function associated with this route.

func (*RouteConfig) GetHTMLHandler added in v0.5.0

func (r *RouteConfig) GetHTMLHandler() HTMLHandler

GetHTMLHandler returns the HTML handler function associated with this route.

func (*RouteConfig) GetHandler added in v0.5.0

func (r *RouteConfig) GetHandler() Handler

GetHandler returns the handler function associated with this route.

func (*RouteConfig) GetJSHandler added in v0.5.0

func (r *RouteConfig) GetJSHandler() JSHandler

GetJSHandler returns the JavaScript handler function associated with this route.

func (*RouteConfig) GetJSONHandler added in v0.5.0

func (r *RouteConfig) GetJSONHandler() JSONHandler

GetJSONHandler returns the JSON handler function associated with this route.

func (*RouteConfig) GetMetadata added in v0.5.0

func (r *RouteConfig) GetMetadata() map[string]interface{}

GetMetadata returns the metadata associated with this route.

func (*RouteConfig) GetMethod added in v0.5.0

func (r *RouteConfig) GetMethod() string

GetMethod returns the HTTP method associated with this route.

func (*RouteConfig) GetName added in v0.5.0

func (r *RouteConfig) GetName() string

GetName returns the name associated with this route.

func (*RouteConfig) GetPath added in v0.5.0

func (r *RouteConfig) GetPath() string

GetPath returns the URL path pattern associated with this route.

func (*RouteConfig) GetStringHandler added in v0.5.0

func (r *RouteConfig) GetStringHandler() StringHandler

GetStringHandler returns the string handler function associated with this route.

func (*RouteConfig) GetTextHandler added in v0.5.0

func (r *RouteConfig) GetTextHandler() TextHandler

GetTextHandler returns the text handler function associated with this route.

func (*RouteConfig) GetXMLHandler added in v0.5.0

func (r *RouteConfig) GetXMLHandler() XMLHandler

GetXMLHandler returns the XML handler function associated with this route.

func (*RouteConfig) SetCSSHandler added in v0.5.0

func (r *RouteConfig) SetCSSHandler(handler CSSHandler) RouteInterface

SetCSSHandler sets the CSS handler function for this route and returns the route for method chaining.

func (*RouteConfig) SetErrorHandler added in v0.5.0

func (r *RouteConfig) SetErrorHandler(handler ErrorHandler) RouteInterface

SetErrorHandler sets the error handler function for this route and returns the route for method chaining.

func (*RouteConfig) SetHTMLHandler added in v0.5.0

func (r *RouteConfig) SetHTMLHandler(handler HTMLHandler) RouteInterface

SetHTMLHandler sets the HTML handler function for this route and returns the route for method chaining.

func (*RouteConfig) SetHandler added in v0.5.0

func (r *RouteConfig) SetHandler(handler Handler) RouteInterface

SetHandler sets the handler function for this route and returns the route for method chaining.

func (*RouteConfig) SetJSHandler added in v0.5.0

func (r *RouteConfig) SetJSHandler(handler JSHandler) RouteInterface

SetJSHandler sets the JavaScript handler function for this route and returns the route for method chaining.

func (*RouteConfig) SetJSONHandler added in v0.5.0

func (r *RouteConfig) SetJSONHandler(handler JSONHandler) RouteInterface

SetJSONHandler sets the JSON handler function for this route and returns the route for method chaining.

func (*RouteConfig) SetMetadata added in v0.5.0

func (r *RouteConfig) SetMetadata(metadata map[string]interface{}) RouteInterface

SetMetadata sets the metadata for this route and returns the route for method chaining.

func (*RouteConfig) SetMethod added in v0.5.0

func (r *RouteConfig) SetMethod(method string) RouteInterface

SetMethod sets the HTTP method for this route and returns the route for method chaining.

func (*RouteConfig) SetName added in v0.5.0

func (r *RouteConfig) SetName(name string) RouteInterface

SetName sets the name for this route and returns the route for method chaining.

func (*RouteConfig) SetPath added in v0.5.0

func (r *RouteConfig) SetPath(path string) RouteInterface

SetPath sets the URL path pattern for this route and returns the route for method chaining.

func (*RouteConfig) SetStringHandler added in v0.5.0

func (r *RouteConfig) SetStringHandler(handler StringHandler) RouteInterface

SetStringHandler sets the string handler function for this route and returns the route for method chaining.

func (*RouteConfig) SetTextHandler added in v0.5.0

func (r *RouteConfig) SetTextHandler(handler TextHandler) RouteInterface

SetTextHandler sets the text handler function for this route and returns the route for method chaining.

func (*RouteConfig) SetXMLHandler added in v0.5.0

func (r *RouteConfig) SetXMLHandler(handler XMLHandler) RouteInterface

SetXMLHandler sets the XML handler function for this route and returns the route for method chaining.

func (RouteConfig) WithAfterMiddleware added in v0.3.0

func (r RouteConfig) WithAfterMiddleware(middleware ...Middleware) RouteConfig

WithAfterMiddleware adds after middleware to a route configuration

func (RouteConfig) WithBeforeMiddleware added in v0.3.0

func (r RouteConfig) WithBeforeMiddleware(middleware ...Middleware) RouteConfig

WithBeforeMiddleware adds before middleware to a route configuration

func (RouteConfig) WithMetadata added in v0.3.0

func (r RouteConfig) WithMetadata(key string, value interface{}) RouteConfig

WithMetadata adds metadata to a route configuration

func (RouteConfig) WithName added in v0.3.0

func (r RouteConfig) WithName(name string) RouteConfig

WithName adds a name to a route configuration

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() Handler
	// SetHandler sets the handler function for this route and returns the route for method chaining.
	SetHandler(handler Handler) 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 []Middleware) RouteInterface
	// GetBeforeMiddlewares returns all middleware functions that will be executed before the route handler.
	GetBeforeMiddlewares() []Middleware

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

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 Handler) 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 Handler) 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 Handler) 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 Handler) 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 RouterConfig added in v0.3.0

type RouterConfig struct {
	Name             string                 `json:"name,omitempty"`
	Prefix           string                 `json:"prefix,omitempty"`
	Routes           []RouteConfig          `json:"routes,omitempty"`
	Groups           []GroupConfig          `json:"groups,omitempty"`
	Domains          []DomainConfig         `json:"domains,omitempty"`
	BeforeMiddleware []Middleware           `json:"-"`
	AfterMiddleware  []Middleware           `json:"-"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

RouterConfig represents a complete declarative router configuration

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 functions to be executed before any route handler.
	// The middleware functions will be executed in the order they are added.
	// Returns the router for method chaining.
	AddBeforeMiddlewares(middleware []Middleware) RouterInterface
	// GetBeforeMiddlewares returns all middleware functions that will be executed before any route handler.
	// Returns a slice of Middleware functions.
	GetBeforeMiddlewares() []Middleware

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

	// 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. By default, it includes recovery middleware to handle panics.

func NewRouterFromConfig added in v0.3.0

func NewRouterFromConfig(config RouterConfig) RouterInterface

NewRouterFromConfig creates a router from a declarative configuration

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
basic command
declarative command
domain command
handlers command
path-parameters command

Jump to

Keyboard shortcuts

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