router

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 14 Imported by: 0

README

ForgeUI Router

Production-ready HTTP routing system for ForgeUI applications.

Features

  • Pattern Matching: Static routes, path parameters (:id), and wildcards (*path)
  • HTTP Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD
  • Middleware: Global and route-specific middleware with chainable execution
  • Named Routes: URL generation from route names
  • PageContext: Rich request context with params, query, headers, cookies
  • Type Safety: Full Go type safety with gomponents integration
  • Priority Routing: Automatic route prioritization (static > params > wildcards)

Quick Start

package main

import (
    "github.com/xraph/forgeui"
    "github.com/xraph/forgeui/router"
    g "maragu.dev/gomponents"
    "maragu.dev/gomponents/html"
)

func main() {
    app := forgeui.New()

    // Register routes
    app.Get("/", HomePage)
    app.Get("/users/:id", UserProfile)
    app.Post("/users", CreateUser)

    // Start server
    http.ListenAndServe(":8080", app.Router())
}

func HomePage(ctx *router.PageContext) (g.Node, error) {
    return html.H1(g.Text("Welcome to ForgeUI")), nil
}

func UserProfile(ctx *router.PageContext) (g.Node, error) {
    id := ctx.Param("id")
    return html.Div(
        html.H1(g.Textf("User #%s", id)),
    ), nil
}

func CreateUser(ctx *router.PageContext) (g.Node, error) {
    return html.P(g.Text("User created")), nil
}

Route Patterns

Static Routes
app.Get("/about", AboutPage)
app.Get("/contact", ContactPage)
Path Parameters
// Single parameter
app.Get("/users/:id", UserProfile)

// Multiple parameters
app.Get("/users/:userId/posts/:postId", PostDetail)
Wildcards
// Matches /files/docs/readme.md, /files/images/logo.png, etc.
app.Get("/files/*filepath", ServeFile)

HTTP Methods

app.Get("/users", ListUsers)
app.Post("/users", CreateUser)
app.Put("/users/:id", UpdateUser)
app.Patch("/users/:id", PatchUser)
app.Delete("/users/:id", DeleteUser)
app.Options("/users", OptionsUsers)
app.Head("/users", HeadUsers)

// Multiple methods on same route
app.Match([]string{"GET", "POST"}, "/api", APIHandler)

PageContext

The PageContext provides access to request data and utilities:

Path Parameters
func UserProfile(ctx *router.PageContext) (g.Node, error) {
    id := ctx.Param("id")                    // String
    userID, err := ctx.ParamInt("id")        // Integer
    userID64, err := ctx.ParamInt64("id")    // Int64
    
    // ...
}
Query Parameters
func SearchUsers(ctx *router.PageContext) (g.Node, error) {
    query := ctx.Query("q")                       // String
    page, err := ctx.QueryInt("page")             // Integer
    limit := ctx.QueryDefault("limit", "10")      // With default
    active := ctx.QueryBool("active")             // Boolean
    
    // ...
}
Headers & Cookies
func Protected(ctx *router.PageContext) (g.Node, error) {
    auth := ctx.Header("Authorization")
    
    cookie, err := ctx.Cookie("session")
    if err != nil {
        // Handle missing cookie
    }
    
    // Set response headers
    ctx.SetHeader("X-Custom", "value")
    
    // Set cookies
    ctx.SetCookie(&http.Cookie{
        Name:  "session",
        Value: "abc123",
    })
    
    // ...
}
Context Values

Store and retrieve values for the request lifecycle:

// In middleware
func AuthMiddleware(next router.PageHandler) router.PageHandler {
    return func(ctx *router.PageContext) (g.Node, error) {
        ctx.Set("user_id", 42)
        ctx.Set("username", "john")
        return next(ctx)
    }
}

// In handler
func Profile(ctx *router.PageContext) (g.Node, error) {
    userID := ctx.GetInt("user_id")
    username := ctx.GetString("username")
    
    // ...
}
Request Information
method := ctx.Method()        // HTTP method
path := ctx.Path()            // URL path
host := ctx.Host()            // Host header
isSecure := ctx.IsSecure()    // HTTPS check
clientIP := ctx.ClientIP()    // Client IP (respects X-Forwarded-For)

Middleware

Global Middleware

Applied to all routes:

app.Use(router.Logger())
app.Use(router.Recovery())
app.Use(router.RequestID())
Route-Specific Middleware

Applied to individual routes:

route := app.Get("/admin", AdminDashboard)
route.WithMiddleware(AuthMiddleware)
Built-in Middleware
// Logging
app.Use(router.Logger())

// Panic recovery
app.Use(router.Recovery())

// CORS
app.Use(router.CORS("*"))

// Request ID
app.Use(router.RequestID())

// Basic authentication
app.Use(router.BasicAuth("admin", "secret"))

// Method restriction
app.Use(router.RequireMethod("GET", "POST"))

// Custom headers
app.Use(router.SetHeader("X-Frame-Options", "DENY"))

// Request timeout
app.Use(router.Timeout(30 * time.Second))
Custom Middleware
func AuthMiddleware(next router.PageHandler) router.PageHandler {
    return func(ctx *router.PageContext) (g.Node, error) {
        // Check authentication
        token := ctx.Header("Authorization")
        if token == "" {
            ctx.ResponseWriter.WriteHeader(http.StatusUnauthorized)
            return html.P(g.Text("Unauthorized")), nil
        }
        
        // Continue to next handler
        return next(ctx)
    }
}

app.Use(AuthMiddleware)
Chaining Middleware
middleware := router.Chain(
    router.Logger(),
    router.Recovery(),
    router.RequestID(),
)

app.Use(middleware)

Named Routes & URL Generation

// Register named route
route := app.Get("/users/:id/posts/:postId", PostDetail)
app.Router().Name("user.post", route)

// Generate URL
url := app.Router().URL("user.post", 123, 456)
// Returns: "/users/123/posts/456"

// In templates
link := html.A(
    html.Href(app.Router().URL("user.post", userID, postID)),
    g.Text("View Post"),
)

Router Options

router := router.New(
    router.WithBasePath("/api/v1"),
    router.WithNotFound(Custom404Handler),
    router.WithErrorHandler(CustomErrorHandler),
)
Custom 404 Handler
func Custom404(ctx *router.PageContext) (g.Node, error) {
    ctx.ResponseWriter.WriteHeader(404)
    return html.Div(
        html.H1(g.Text("Page Not Found")),
        html.P(g.Text("The page you're looking for doesn't exist.")),
    ), nil
}

router := router.New(router.WithNotFound(Custom404))
Custom Error Handler
func CustomError(ctx *router.PageContext, err error) g.Node {
    ctx.ResponseWriter.WriteHeader(500)
    return html.Div(
        html.H1(g.Text("Something went wrong")),
        html.P(g.Text(err.Error())),
    )
}

router := router.New(router.WithErrorHandler(CustomError))

Testing

The router is designed for easy testing with httptest:

func TestUserProfile(t *testing.T) {
    r := router.New()
    r.Get("/users/:id", UserProfile)
    
    req := httptest.NewRequest("GET", "/users/123", nil)
    w := httptest.NewRecorder()
    
    r.ServeHTTP(w, req)
    
    if w.Code != http.StatusOK {
        t.Errorf("Expected 200, got %d", w.Code)
    }
}

Best Practices

  1. Use middleware for cross-cutting concerns: Authentication, logging, CORS
  2. Keep handlers focused: One responsibility per handler
  3. Return errors: Let the error handler deal with them
  4. Use named routes: Makes refactoring easier
  5. Test with httptest: Fast, reliable, no network needed
  6. Set appropriate status codes: Use ctx.ResponseWriter.WriteHeader()
  7. Validate input: Check params and query values before use

Performance

  • Routes are sorted by priority at registration time
  • Pattern matching uses compiled regex
  • Middleware chains are built once per route
  • Zero allocations for static routes
  • Thread-safe route registration and lookup

Integration with ForgeUI

The router is fully integrated with ForgeUI's App struct:

app := forgeui.New()

// These are equivalent:
app.Get("/users", ListUsers)
app.Router().Get("/users", ListUsers)

// Access router directly for advanced features:
app.Router().Use(middleware...)
app.Router().Name("route.name", route)

Examples

See the example directory for complete working examples.

Documentation

Index

Constants

View Source
const (
	MethodGet     = http.MethodGet
	MethodPost    = http.MethodPost
	MethodPut     = http.MethodPut
	MethodPatch   = http.MethodPatch
	MethodDelete  = http.MethodDelete
	MethodOptions = http.MethodOptions
	MethodHead    = http.MethodHead
)

HTTP method constants

View Source
const LoaderTimeout = 30 * time.Second

LoaderTimeout is the default timeout for data loaders

Variables

This section is empty.

Functions

func BlankLayout

func BlankLayout(ctx *PageContext, content g.Node) g.Node

BlankLayout provides minimal layout (just wraps content in HTML structure)

func DashboardLayout

func DashboardLayout(ctx *PageContext, content g.Node) g.Node

DashboardLayout provides a typical dashboard layout structure

func DefaultLayout

func DefaultLayout(ctx *PageContext, content g.Node) g.Node

DefaultLayout provides a basic HTML5 layout

func Error403

func Error403(message string) error

Error403 is a convenience function for returning a 403 error

func Error404

func Error404(message string) error

Error404 is a convenience function for returning a 404 error

func Error500

func Error500(message string, err error) error

Error500 is a convenience function for returning a 500 error

Types

type ErrorHandler

type ErrorHandler func(*PageContext, error) g.Node

ErrorHandler handles errors that occur during request processing

type Group

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

Group represents a group of routes with shared configuration Renamed from RouteGroup for cleaner API

func (*Group) Delete

func (g *Group) Delete(pattern string, handler PageHandler) *Route

Delete registers a DELETE route in the group

func (*Group) Get

func (g *Group) Get(pattern string, handler PageHandler) *Route

Get registers a GET route in the group

func (*Group) Group

func (g *Group) Group(prefix string, opts ...GroupOption) *Group

Group creates a nested route group

func (*Group) Head

func (g *Group) Head(pattern string, handler PageHandler) *Route

Head registers a HEAD route in the group

func (*Group) Layout

func (g *Group) Layout(layout string) *Group

Layout sets the layout for this group (fluent API)

func (*Group) Middleware

func (g *Group) Middleware(middleware ...Middleware) *Group

Middleware adds middleware to this group (fluent API)

func (*Group) Options

func (g *Group) Options(pattern string, handler PageHandler) *Route

Options registers an OPTIONS route in the group

func (*Group) Page added in v0.0.3

func (g *Group) Page(pattern string) *GroupPageBuilder

Page creates a new page builder for this group with fluent API

func (*Group) Patch

func (g *Group) Patch(pattern string, handler PageHandler) *Route

Patch registers a PATCH route in the group

func (*Group) Post

func (g *Group) Post(pattern string, handler PageHandler) *Route

Post registers a POST route in the group

func (*Group) Put

func (g *Group) Put(pattern string, handler PageHandler) *Route

Put registers a PUT route in the group

type GroupOption

type GroupOption func(*Group)

GroupOption configures a Group

func GroupLayout

func GroupLayout(layout string) GroupOption

GroupLayout sets the default layout for all routes in the group

func GroupMiddleware

func GroupMiddleware(middleware ...Middleware) GroupOption

GroupMiddleware adds middleware to all routes in the group

type GroupPageBuilder added in v0.0.3

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

GroupPageBuilder provides a fluent API for building and registering pages within a group

func (*GroupPageBuilder) DELETE added in v0.0.3

func (gpb *GroupPageBuilder) DELETE() *GroupPageBuilder

DELETE is a convenience method to set method to DELETE

func (*GroupPageBuilder) GET added in v0.0.3

func (gpb *GroupPageBuilder) GET() *GroupPageBuilder

GET is a convenience method to set method to GET

func (*GroupPageBuilder) Handler added in v0.0.3

func (gpb *GroupPageBuilder) Handler(handler PageHandler) *GroupPageBuilder

Handler sets the page handler function

func (*GroupPageBuilder) Layout added in v0.0.3

func (gpb *GroupPageBuilder) Layout(layout string) *GroupPageBuilder

Layout sets the layout name for this page

func (*GroupPageBuilder) Loader added in v0.0.3

func (gpb *GroupPageBuilder) Loader(loader LoaderFunc) *GroupPageBuilder

Loader sets the data loader function

func (*GroupPageBuilder) Meta added in v0.0.3

func (gpb *GroupPageBuilder) Meta(title, description string) *GroupPageBuilder

Meta sets the page metadata (title and description)

func (*GroupPageBuilder) MetaFull added in v0.0.3

func (gpb *GroupPageBuilder) MetaFull(meta *RouteMeta) *GroupPageBuilder

MetaFull sets complete page metadata

func (*GroupPageBuilder) Method added in v0.0.3

func (gpb *GroupPageBuilder) Method(method string) *GroupPageBuilder

Method sets the HTTP method for this page

func (*GroupPageBuilder) Middleware added in v0.0.3

func (gpb *GroupPageBuilder) Middleware(middleware ...Middleware) *GroupPageBuilder

Middleware adds middleware to this page

func (*GroupPageBuilder) Name added in v0.0.3

func (gpb *GroupPageBuilder) Name(name string) *GroupPageBuilder

Name sets a name for this route (for URL generation)

func (*GroupPageBuilder) NoLayout added in v0.0.3

func (gpb *GroupPageBuilder) NoLayout() *GroupPageBuilder

NoLayout disables layout for this page

func (*GroupPageBuilder) PATCH added in v0.0.3

func (gpb *GroupPageBuilder) PATCH() *GroupPageBuilder

PATCH is a convenience method to set method to PATCH

func (*GroupPageBuilder) POST added in v0.0.3

func (gpb *GroupPageBuilder) POST() *GroupPageBuilder

POST is a convenience method to set method to POST

func (*GroupPageBuilder) PUT added in v0.0.3

func (gpb *GroupPageBuilder) PUT() *GroupPageBuilder

PUT is a convenience method to set method to PUT

func (*GroupPageBuilder) Register added in v0.0.3

func (gpb *GroupPageBuilder) Register() *Route

Register registers the page with the router through the group

type LayoutConfig

type LayoutConfig struct {
	Fn     LayoutFunc
	Parent string
}

LayoutConfig holds layout configuration including parent relationship

type LayoutFunc

type LayoutFunc func(ctx *PageContext, content g.Node) g.Node

LayoutFunc wraps page content with a layout

type LayoutOption

type LayoutOption func(*LayoutConfig)

LayoutOption configures a layout

func WithParentLayout

func WithParentLayout(parent string) LayoutOption

WithParentLayout sets the parent layout for composition

type LoaderError

type LoaderError struct {
	Status  int
	Message string
	Err     error
}

LoaderError represents an error that occurred during data loading

func (*LoaderError) Error

func (e *LoaderError) Error() string

Error implements the error interface

func (*LoaderError) Unwrap

func (e *LoaderError) Unwrap() error

Unwrap returns the underlying error

type LoaderFunc

type LoaderFunc func(ctx context.Context, params Params) (any, error)

LoaderFunc loads data before rendering a page

type Middleware

type Middleware func(PageHandler) PageHandler

Middleware is a function that wraps a PageHandler

func BasicAuth

func BasicAuth(username, password string) Middleware

BasicAuth returns middleware that requires HTTP basic authentication

func CORS

func CORS(allowOrigin string) Middleware

CORS returns middleware that adds CORS headers

func Chain

func Chain(middleware ...Middleware) Middleware

Chain chains multiple middleware into one

func Logger

func Logger() Middleware

Logger returns middleware that logs requests

func Recovery

func Recovery() Middleware

Recovery returns middleware that recovers from panics

func RequestID

func RequestID() Middleware

RequestID returns middleware that adds a unique request ID

func RequireMethod

func RequireMethod(methods ...string) Middleware

RequireMethod returns middleware that only allows specific HTTP methods

func SetHeader

func SetHeader(key, value string) Middleware

SetHeader returns middleware that sets a response header

func Timeout

func Timeout(duration time.Duration) Middleware

Timeout returns middleware that enforces a timeout on requests

type PageContext

type PageContext struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	Params         Params

	LoadedData any
	Meta       *RouteMeta
	// contains filtered or unexported fields
}

PageContext wraps the HTTP request and response with additional utilities

func (*PageContext) App

func (c *PageContext) App() any

App returns the application instance Returns interface{} to avoid circular dependency - cast to *forgeui.App in usage

func (*PageContext) ClientIP

func (c *PageContext) ClientIP() string

ClientIP returns the client's IP address (best effort)

func (*PageContext) Context

func (c *PageContext) Context() context.Context

Context returns the request's context

func (*PageContext) Cookie

func (c *PageContext) Cookie(name string) (*http.Cookie, error)

Cookie retrieves a cookie by name

func (*PageContext) Get

func (c *PageContext) Get(key string) (any, bool)

Get retrieves a value from the context

func (*PageContext) GetInt

func (c *PageContext) GetInt(key string) int

GetInt retrieves an integer value from the context

func (*PageContext) GetMeta

func (c *PageContext) GetMeta() *RouteMeta

GetMeta returns the route's metadata

func (*PageContext) GetString

func (c *PageContext) GetString(key string) string

GetString retrieves a string value from the context

func (*PageContext) Header

func (c *PageContext) Header(key string) string

Header retrieves a request header by key

func (*PageContext) Host

func (c *PageContext) Host() string

Host returns the host of the request

func (*PageContext) IsSecure

func (c *PageContext) IsSecure() bool

IsSecure returns true if the request is over HTTPS

func (*PageContext) LoaderData

func (c *PageContext) LoaderData() any

LoaderData returns the data loaded by the route's loader

func (*PageContext) Method

func (c *PageContext) Method() string

Method returns the HTTP method of the request

func (*PageContext) Param

func (c *PageContext) Param(key string) string

Param retrieves a path parameter by key

func (*PageContext) ParamInt

func (c *PageContext) ParamInt(key string) (int, error)

ParamInt retrieves a path parameter as an integer

func (*PageContext) ParamInt64

func (c *PageContext) ParamInt64(key string) (int64, error)

ParamInt64 retrieves a path parameter as an int64

func (*PageContext) Path

func (c *PageContext) Path() string

Path returns the URL path of the request

func (*PageContext) Query

func (c *PageContext) Query(key string) string

Query retrieves a query parameter by key

func (*PageContext) QueryBool

func (c *PageContext) QueryBool(key string) bool

QueryBool retrieves a query parameter as a boolean

func (*PageContext) QueryDefault

func (c *PageContext) QueryDefault(key, defaultVal string) string

QueryDefault retrieves a query parameter with a default value

func (*PageContext) QueryInt

func (c *PageContext) QueryInt(key string) (int, error)

QueryInt retrieves a query parameter as an integer

func (*PageContext) QueryInt64

func (c *PageContext) QueryInt64(key string) (int64, error)

QueryInt64 retrieves a query parameter as an int64

func (*PageContext) Set

func (c *PageContext) Set(key string, value any)

Set stores a value in the context for the duration of the request

func (*PageContext) SetCookie

func (c *PageContext) SetCookie(cookie *http.Cookie)

SetCookie sets a cookie in the response

func (*PageContext) SetHeader

func (c *PageContext) SetHeader(key, value string)

SetHeader sets a response header

func (*PageContext) WithContext

func (c *PageContext) WithContext(ctx context.Context) *PageContext

WithContext returns a shallow copy of PageContext with a new context

type PageHandler

type PageHandler func(*PageContext) (g.Node, error)

PageHandler is a function that handles a page request and returns a Node for rendering

func DefaultErrorPage

func DefaultErrorPage(status int) PageHandler

DefaultErrorPage returns a default error page for the given status code

func HandlerFunc

func HandlerFunc(fn http.HandlerFunc) PageHandler

HandlerFunc converts a standard http.HandlerFunc to a PageHandler This is useful for integrating with existing HTTP handlers that don't return nodes

type ParamKey

type ParamKey string

ParamKey is the type for parameter keys

type Params

type Params map[string]string

Params stores route parameters extracted from the URL path

func (Params) Get

func (p Params) Get(key string) string

Get retrieves a parameter value by key

func (Params) Has

func (p Params) Has(key string) bool

Has checks if a parameter exists

type Route

type Route struct {
	Pattern    string
	Method     string
	Handler    PageHandler
	Middleware []Middleware
	Name       string
	Layout     string
	LoaderFn   LoaderFunc
	Metadata   *RouteMeta
	// contains filtered or unexported fields
}

Route represents a single route in the router

func (*Route) Description

func (r *Route) Description(desc string) *Route

Description sets just the description metadata

func (*Route) Keywords

func (r *Route) Keywords(keywords ...string) *Route

Keywords sets the keywords metadata

func (*Route) Loader

func (r *Route) Loader(fn LoaderFunc) *Route

Loader sets the data loader for a route

func (*Route) Match

func (r *Route) Match(path string) (params Params, ok bool)

Match checks if the given path matches this route and extracts parameters

func (*Route) Meta

func (r *Route) Meta(meta RouteMeta) *Route

Meta sets the metadata for a route

func (*Route) NoIndex

func (r *Route) NoIndex() *Route

NoIndex marks the page as no-index for search engines

func (*Route) NoLayout

func (r *Route) NoLayout() *Route

NoLayout explicitly disables layout for a route

func (*Route) OGImage

func (r *Route) OGImage(url string) *Route

OGImage sets the Open Graph image

func (*Route) SetLayout

func (r *Route) SetLayout(name string) *Route

SetLayout sets the layout for a route

func (*Route) Title

func (r *Route) Title(title string) *Route

Title sets just the title metadata

func (*Route) URL

func (r *Route) URL(params ...any) string

URL generates a URL from this route's pattern with the given parameters

func (*Route) URLMap

func (r *Route) URLMap(params map[string]any) string

URLMap generates a URL from this route's pattern with named parameters Example: route.URLMap(map[string]interface{}{"id": 123, "action": "edit"})

func (*Route) WithLoader

func (r *Route) WithLoader(loader LoaderFunc) *Route

WithLoader sets the loader function for this route

func (*Route) WithMeta

func (r *Route) WithMeta(meta *RouteMeta) *Route

WithMeta sets the metadata for this route

func (*Route) WithMiddleware

func (r *Route) WithMiddleware(middleware ...Middleware) *Route

WithMiddleware adds middleware to this route

func (*Route) WithName

func (r *Route) WithName(name string) *Route

WithName sets the name of this route

type RouteBuilder

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

RouteBuilder provides a fluent API for building routes

func (*RouteBuilder) Build

func (b *RouteBuilder) Build() *Route

Build finalizes the route (no-op, for API consistency)

func (*RouteBuilder) Handler

func (b *RouteBuilder) Handler(handler PageHandler) *RouteBuilder

Handler sets the handler function (optional, used if handler not set during registration)

func (*RouteBuilder) Middleware

func (b *RouteBuilder) Middleware(middleware ...Middleware) *RouteBuilder

Middleware adds middleware to this specific route

func (*RouteBuilder) Name

func (b *RouteBuilder) Name(name string) *RouteBuilder

Name sets the name of the route for URL generation

type RouteGroup

type RouteGroup = Group

RouteGroup is an alias for Group (backward compatibility)

type RouteMeta

type RouteMeta struct {
	Title        string
	Description  string
	Keywords     []string
	OGImage      string
	OGType       string
	CanonicalURL string
	NoIndex      bool
}

RouteMeta contains SEO and page metadata

func (*RouteMeta) MetaTags

func (m *RouteMeta) MetaTags() []g.Node

MetaTags generates HTML meta tags from the metadata

type Router

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

Router handles HTTP routing for ForgeUI applications

func New

func New(opts ...RouterOption) *Router

New creates a new router with optional configuration

func (*Router) Delete

func (r *Router) Delete(pattern string, handler PageHandler) *Route

Delete registers a DELETE route

func (*Router) Get

func (r *Router) Get(pattern string, handler PageHandler) *Route

Get registers a GET route

func (*Router) GetLayout

func (r *Router) GetLayout(name string) (LayoutFunc, bool)

GetLayout retrieves a layout by name

func (*Router) Group

func (r *Router) Group(prefix string, opts ...GroupOption) *Group

Group creates a new route group with a common prefix and options

func (*Router) Handle

func (r *Router) Handle(method, pattern string, handler PageHandler) *Route

Handle registers a route with the given method, pattern, and handler

func (*Router) Head

func (r *Router) Head(pattern string, handler PageHandler) *Route

Head registers a HEAD route

func (*Router) Match

func (r *Router) Match(methods []string, pattern string, handler PageHandler) []*Route

Match registers a route that matches multiple HTTP methods

func (*Router) Name

func (r *Router) Name(name string, route *Route)

Name registers a named route for URL generation

func (*Router) Options

func (r *Router) Options(pattern string, handler PageHandler) *Route

Options registers an OPTIONS route

func (*Router) Patch

func (r *Router) Patch(pattern string, handler PageHandler) *Route

Patch registers a PATCH route

func (*Router) Post

func (r *Router) Post(pattern string, handler PageHandler) *Route

Post registers a POST route

func (*Router) Put

func (r *Router) Put(pattern string, handler PageHandler) *Route

Put registers a PUT route

func (*Router) RegisterLayout

func (r *Router) RegisterLayout(name string, fn LayoutFunc, opts ...LayoutOption)

RegisterLayout registers a named layout with optional parent

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler interface

func (*Router) SetApp

func (r *Router) SetApp(app any)

SetApp sets the app reference for PageContext

func (*Router) SetDefaultLayout

func (r *Router) SetDefaultLayout(name string)

SetDefaultLayout sets the default layout for all routes

func (*Router) SetErrorPage

func (r *Router) SetErrorPage(status int, handler PageHandler)

SetErrorPage registers a custom error page for a specific status code

func (*Router) URL

func (r *Router) URL(name string, params ...any) string

URL generates a URL for a named route with the given parameters Example: router.URL("user", 123) -> "/users/123"

func (*Router) Use

func (r *Router) Use(middleware ...Middleware) *Router

Use adds global middleware to the router

type RouterOption

type RouterOption func(*Router)

RouterOption is a functional option for configuring the Router

func WithBasePath

func WithBasePath(path string) RouterOption

WithBasePath sets a base path for all routes

func WithErrorHandler

func WithErrorHandler(handler ErrorHandler) RouterOption

WithErrorHandler sets a custom error handler

func WithNotFound

func WithNotFound(handler PageHandler) RouterOption

WithNotFound sets a custom 404 handler

Jump to

Keyboard shortcuts

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