nanite

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 20 Imported by: 1

README

Nanite

Go Reference Go Report Card

A lightweight, high-performance HTTP router for Go. Designed to be developer-friendly with an Express.js-inspired API, without sacrificing speed.

Performance

Microbenchmarks

go test ./benchmark -benchmem, Apple M2, Go 1.25.1:

net/http comparison

Framework Static ns/op Static allocs/op Param ns/op Param allocs/op
Nanite ~654 0 ~491 0
httprouter ~159 0 ~259 5
chi ~1136 16 ~1361 20
gorilla/mux ~3452 56 ~3577 40
fiber (net/http adaptor) ~7010 152 ~4910 95

Nanite vs Fiber (native, no adaptor)

Framework Static ns/op Static allocs/op Param ns/op Param allocs/op
Nanite ~653 0 ~549 0
Fiber (native) ~2220 8 ~1801 5

Nanite achieves zero allocations on both static and param routes.

Load Test (wrk)
Route Type Throughput p99 Latency
Static 183,120 req/s 13.72ms
Param 180,619 req/s 15.20ms

Microbenchmarks are in-process. Load tests run against a live server. Fiber adapter numbers include net/http adapter overhead.

Installation

go get github.com/xDarkicex/nanite
# Optional websocket module
go get github.com/xDarkicex/nanite/websocket
# Optional QUIC / HTTP/3 module
go get github.com/xDarkicex/nanite/quic

Module Layout

  • github.com/xDarkicex/nanite — core router/framework (no websocket dependency in core package)
  • github.com/xDarkicex/nanite/websocket — optional websocket integration module
  • github.com/xDarkicex/nanite/quic — optional HTTP/3 (QUIC) transport module

This keeps core focused and lets users opt into websocket and HTTP/3 transport features only when needed.

Quick Start

package main

import (
    "net/http"
    "time"

    "github.com/xDarkicex/nanite"
)

func main() {
    r := nanite.New(
        nanite.WithPanicRecovery(true),
        nanite.WithServerTimeouts(5*time.Second, 60*time.Second, 60*time.Second),
        nanite.WithRouteCacheOptions(1024, 10),
        nanite.WithRouteCacheTuning(4, 8),
    )

    r.Get("/hello", func(c *nanite.Context) {
        c.String(http.StatusOK, "Hello, World!")
    })

    r.Start("8080")
}

Features

  • Radix Tree Routing — prefix-compressed tree for fast static and dynamic route matching
  • Zero-Allocation Path Parsing — URL parameters extracted with no heap pressure
  • Request Routing Cache — frequently accessed routes bypass tree traversal entirely
  • Buffered Response Writer — optimized I/O with tracked status and pooled buffers
  • Object Pooling — extensive sync.Pool use across contexts, writers, and validation
  • Express-Like Middleware — global and per-route middleware with next() chaining
  • Fluent Middleware API — chainable middleware composition
  • High-Performance Validation — pre-allocated error structs, no reflection on the hot path
  • Enhanced Parameter Handling — complex route parameters with wildcard and typed support
  • Built-in CORS — preflight short-circuit, returns 204 and halts chain
  • Route Groups — shared prefix and middleware scoping
  • WebSockets — optional nanite/websocket package
  • Static File Serving — buffered I/O with efficient path resolution

Configuration

r := nanite.New(
    nanite.WithPanicRecovery(false),
    nanite.WithRouteCacheOptions(2048, 10),
    nanite.WithRouteCacheTuning(8, 16),
    nanite.WithServerTimeouts(3*time.Second, 30*time.Second, 30*time.Second),
    nanite.WithServerMaxHeaderBytes(1<<20),
    nanite.WithTCPBufferSizes(65536, 65536),
)

Routing

r.Get("/users", listUsers)
r.Post("/users", createUser)
r.Put("/users/:id", updateUser)
r.Delete("/users/:id", deleteUser)

// Route parameters
r.Get("/users/:id", func(c *nanite.Context) {
    id, _ := c.GetParam("id")
    c.JSON(http.StatusOK, map[string]string{"id": id})
})

// Wildcard routes
r.Get("/files/*path", func(c *nanite.Context) {
    path, _ := c.GetParam("path")
    c.JSON(http.StatusOK, map[string]string{"path": path})
})

Google-style custom method suffix routes (AIP-136):

r.Post("/v1/projects/:name:undelete", func(c *nanite.Context) {
    name, _ := c.GetParam("name") // "proj123" from "/v1/projects/proj123:undelete"
    c.String(http.StatusOK, name)
})

// Plain and suffixed params can coexist at the same depth.
r.Post("/users/:id", plainHandler)
r.Post("/users/:id:undelete", undeleteHandler)

Named routes and reverse routing:

r.Get("/users/:id", showUser).Name("users.show")
r.Get("/files/*path", showFile).Name("files.show")

userURL, _ := r.URL("users.show", map[string]string{"id": "42"})
// /users/42

fileURL, _ := r.URL("files.show", map[string]string{"path": "docs/report.pdf"})
// /files/docs/report.pdf

usersURL, _ := r.URLWithQuery(
    "users.show",
    map[string]string{"id": "42"},
    map[string]string{"tab": "activity", "limit": "20"},
)
// /users/42?limit=20&tab=activity

Middleware

// Global
r.Use(LoggerMiddleware)

// Per-route
r.Get("/admin", adminHandler, AuthMiddleware)

// Middleware signature
func LoggerMiddleware(c *nanite.Context, next func()) {
    start := time.Now()
    next()
    fmt.Printf("[%s] %s %dms\n", c.Request.Method, c.Request.URL.Path, time.Since(start).Milliseconds())
}

CORS

r.Use(nanite.CORSMiddleware(&nanite.CORSConfig{
    AllowOrigins:     []string{"https://app.example.com"},
    AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
    AllowHeaders:     []string{"Content-Type", "Authorization"},
    ExposeHeaders:    []string{"X-Request-ID"},
    AllowCredentials: true,
    MaxAge:           600,
}))

Security Middleware

Rate limiting (opt-in):

r.Use(nanite.RateLimitMiddleware(&nanite.RateLimitConfig{
    Requests: 120,
    Window:   time.Minute,
}))

CSRF protection (opt-in):

r.Use(nanite.CSRFMiddleware(nil))

Validation

emailRule    := nanite.NewValidationChain("email").Required().IsEmail()
passwordRule := nanite.NewValidationChain("password").Required().Length(8, 64)

r.Post("/register", registerHandler, nanite.ValidationMiddleware(emailRule, passwordRule))

func registerHandler(c *nanite.Context) {
    if !c.CheckValidation() {
        return // response already sent
    }
    // ...
}

Route Groups

api := r.Group("/api/v1")
api.Get("/users", listUsers)
api.Post("/users", createUser)

admin := api.Group("/admin", AuthMiddleware)
admin.Get("/stats", getStats)

WebSockets

import (
    nanitews "github.com/xDarkicex/nanite/websocket"
    "github.com/gorilla/websocket"
)

nanitews.Register(r, "/chat", func(conn *websocket.Conn, c *nanite.Context) {
    for {
        mt, msg, err := conn.ReadMessage()
        if err != nil {
            return
        }
        conn.WriteMessage(mt, msg)
    }
})

Options-based registration:

nanitews.RegisterWithOptions(r, "/events", handler,
    nanitews.WithAllowedOrigins("https://app.example.com"),
    nanitews.WithUpgrader(&websocket.Upgrader{
        HandshakeTimeout: 5 * time.Second,
    }),
)

HTTP/3 (QUIC)

import (
    "net/http"
    "time"

    "github.com/xDarkicex/nanite"
    nanitequic "github.com/xDarkicex/nanite/quic"
    quicgo "github.com/quic-go/quic-go"
)

r := nanite.New()
r.Get("/healthz", func(c *nanite.Context) {
    c.String(http.StatusOK, "ok")
})

qs := nanitequic.New(r, nanitequic.Config{
    Addr:     ":8443",
    CertFile: "server.crt",
    KeyFile:  "server.key",
    QUICConfig: &quicgo.Config{
        MaxIdleTimeout: 15 * time.Second,
    },
    Logger: func(e nanitequic.Event) {
        // e.Component: h1|h3|server, e.Status: started|stopped|error
        // e.Addr, e.Err, e.Time are available for structured logging.
    },
})

// HTTP/3 only
if err := qs.StartHTTP3(); err != nil {
    panic(err)
}

// Graceful shutdown convenience
if err := qs.ShutdownGraceful(5 * time.Second); err != nil {
    panic(err)
}

Router-first helper:

err := nanitequic.StartRouterHTTP3(r, nanitequic.Config{
    Addr:     ":8443",
    CertFile: "server.crt",
    KeyFile:  "server.key",
})
if err != nil {
    panic(err)
}

Dual-stack helper (HTTP/1 + HTTP/3):

err := nanitequic.StartRouterDual(r, nanitequic.Config{
    Addr:      ":8443", // UDP (HTTP/3)
    HTTP1Addr: ":8080", // TCP (HTTP/1.1 / HTTP/2)
    CertFile:  "server.crt",
    KeyFile:   "server.key",
    HTTP1ReadHeaderTimeout: 2 * time.Second,
    HTTP1MaxHeaderBytes:    1 << 20,
    HTTP1DisableKeepAlives: false,
})
if err != nil {
    panic(err)
}

Full dual-stack example:

package main

import (
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"

    "github.com/xDarkicex/nanite"
    nanitequic "github.com/xDarkicex/nanite/quic"
)

func main() {
    r := nanite.New()
    r.Use(nanitequic.AltSvcNaniteMiddleware(nanitequic.AltSvcConfig{
        UDPPort: 8443,
        MaxAge:  300,
    }))
    r.Get("/healthz", func(c *nanite.Context) {
        c.String(http.StatusOK, "ok")
    })

    qs := nanitequic.NewRouterServer(r, nanitequic.Config{
        Addr:                   ":8443", // HTTP/3 over UDP
        HTTP1Addr:              ":8080", // HTTP/1.1+2 over TCP
        CertFile:               "server.crt",
        KeyFile:                "server.key",
        HTTP1ReadHeaderTimeout: 2 * time.Second,
        HTTP1MaxHeaderBytes:    1 << 20,
    })

    go func() {
        if err := qs.StartDualAndServe(); err != nil {
            log.Fatalf("dual-stack server failed: %v", err)
        }
    }()

    sig := make(chan os.Signal, 1)
    signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
    <-sig

    if err := qs.ShutdownGraceful(5 * time.Second); err != nil {
        log.Printf("shutdown error: %v", err)
    }
}

Alt-Svc advertisement middleware:

r.Use(nanitequic.AltSvcNaniteMiddleware(nanitequic.AltSvcConfig{
    UDPPort: 8443,
    MaxAge:  86400,
}))

TLS helpers:

// Early cert/key path validation
if err := nanitequic.ValidateTLSFiles("server.crt", "server.key"); err != nil {
    panic(err)
}

// Optional: build reusable tls.Config for HTTP/3
tlsCfg, err := nanitequic.LoadTLSConfig("server.crt", "server.key", nil)
if err != nil {
    panic(err)
}

qs := nanitequic.New(r, nanitequic.Config{
    Addr:      ":8443",
    TLSConfig: tlsCfg, // uses ListenAndServe with this config
})

Production notes:

  • UDP load balancer: HTTP/3 requires UDP routing. Ensure your LB supports UDP and preserves client source address as needed for QUIC behavior.
  • Firewall and security groups: open both TCP (for HTTP/1.1+2 fallback) and UDP (for HTTP/3), typically same public port.
  • Cert rotation: rotate cert/key atomically on disk and restart gracefully; for advanced rotation, provide TLSConfig with dynamic cert loading.
  • Alt-Svc rollout: start with low MaxAge (for example 60-300s), verify client success/error telemetry, then increase to longer cache durations.
  • Mixed clients: keep dual-stack enabled during rollout since some clients or networks still block UDP/QUIC.

Static Files

r.ServeStatic("/static", "./public")

Context API

// Request
c.Bind(&user)
c.FormValue("name")
c.Query("sort")
c.GetParam("id")
c.File("avatar")

// Response
c.JSON(http.StatusOK, data)
c.String(http.StatusOK, "Hello")
c.HTML(http.StatusOK, "<h1>Hello</h1>")
c.Redirect(http.StatusFound, "/login")
c.SetHeader("X-Custom", "value")
c.Status(http.StatusCreated)
c.Cookie("session", token)

// Scoped data
c.Set("user", user)
if v, ok := c.Get("user"); ok { ... }
c.GetValue("user")

Roadmap

Completed

  • Radix tree routing
  • Zero-allocation path parsing
  • Validation system with pre-allocated errors
  • Buffered response writer
  • Request routing cache
  • Hot path allocation reduction
  • Fluent middleware API
  • Enhanced parameter handling
  • Named routes and reverse routing
  • CSRF and rate limiting middleware

Planned

  • Method-not-allowed (405) + Allow header (opt-in)

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-feature)
  3. Commit your changes (git commit -m 'Add my feature')
  4. Push to the branch (git push origin feature/my-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package nanite provides a high-performance HTTP router with Express-like ergonomics.

Package nanite provides a lightweight, high-performance HTTP router for Go with optimized memory management through sync.Pool implementations.

Index

Constants

View Source
const (
	DefaultBufferSize = 4096 // Default buffer size for most content types
	TextBufferSize    = 2048 // Smaller buffer size for text-based content for faster flushing
	BinaryBufferSize  = 8192 // Larger buffer size for binary content to minimize syscalls
)

Variables

This section is empty.

Functions

func ParseRateLimitRequests

func ParseRateLimitRequests(raw string, fallback int) int

ParseRateLimitRequests parses request limits from string config values.

func ParseRateLimitWindow

func ParseRateLimitWindow(raw string, fallback time.Duration) time.Duration

ParseRateLimitWindow parses duration shorthand used in external config bridges.

Types

type BufferedResponseWriter

type BufferedResponseWriter struct {
	*TrackedResponseWriter
	// contains filtered or unexported fields
}

func (*BufferedResponseWriter) Close

func (w *BufferedResponseWriter) Close()

func (*BufferedResponseWriter) Flush

func (w *BufferedResponseWriter) Flush()

Flush writes buffered data to the underlying ResponseWriter

func (*BufferedResponseWriter) Write

func (w *BufferedResponseWriter) Write(b []byte) (int, error)

type CORSConfig

type CORSConfig struct {
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	ExposeHeaders    []string
	AllowCredentials bool
	MaxAge           int
	AllowOriginFunc  func(origin string) bool
}

CORSConfig controls CORSMiddleware behavior.

func DefaultCORSConfig

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig returns secure default CORS settings.

type CSRFConfig

type CSRFConfig struct {
	CookieName string
	HeaderName string
	FormField  string

	CookiePath     string
	CookieDomain   string
	CookieMaxAge   int
	CookieSecure   bool
	CookieHTTPOnly bool
	CookieSameSite http.SameSite

	TokenLength int

	// UnsafeMethods are protected. Missing map uses POST/PUT/PATCH/DELETE.
	UnsafeMethods map[string]struct{}

	ErrorStatus  int
	ErrorMessage string
	OnError      func(*Context)
}

CSRFConfig controls CSRF middleware behavior.

func DefaultCSRFConfig

func DefaultCSRFConfig() CSRFConfig

DefaultCSRFConfig returns a baseline config suitable for most apps.

type Config

type Config struct {
	NotFoundHandler      HandlerFunc
	ErrorHandler         func(*Context, error)
	RecoverPanics        bool
	RouteCacheSize       int
	RouteMaxParams       int
	RouteCachePromote    uint32
	RouteCacheMinDyn     int
	DefaultBufferSize    int
	TextBufferSize       int
	BinaryBufferSize     int
	AdaptiveBuffering    bool
	ServerReadTimeout    time.Duration
	ServerWriteTimeout   time.Duration
	ServerIdleTimeout    time.Duration
	ServerMaxHeaderBytes int
	TCPReadBuffer        int
	TCPWriteBuffer       int
}

type Context

type Context struct {
	// Core HTTP objects
	Writer  http.ResponseWriter // Underlying response writer for sending HTTP responses
	Request *http.Request       // Original HTTP request with all headers, body, and URL information

	// Reference maps (8-byte pointers)
	Values map[string]interface{} // Thread-safe key-value store for request-scoped data sharing between handlers and middleware

	// Array and slice fields
	Params         [10]Param        // Fixed-size array of route parameters extracted from URL (e.g., /users/:id → {id: "123"})
	ValidationErrs ValidationErrors // Collection of validation failures for providing consistent error responses

	// Integer fields (8 bytes on 64-bit systems)
	ParamsCount int // Number of active parameters in the Params array, avoids unnecessary iterations
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

Abort marks the request as aborted, preventing further processing.

func (*Context) Bind

func (c *Context) Bind(v interface{}) error

Bind decodes the request body into the provided interface.

func (*Context) CheckValidation

func (c *Context) CheckValidation() bool

CheckValidation validates all lazy fields and returns true if validation passed

func (*Context) CleanupPooledResources

func (c *Context) CleanupPooledResources()

CleanupPooledResources returns all pooled resources to their respective pools

func (*Context) ClearLazyFields

func (c *Context) ClearLazyFields()

ClearLazyFields efficiently clears the LazyFields map without reallocating.

func (*Context) ClearValues

func (c *Context) ClearValues()

ClearValues efficiently clears the Values map without reallocating.

func (*Context) Cookie

func (c *Context) Cookie(name, value string, options ...interface{})

Cookie sets a cookie on the response.

func (*Context) Error

func (c *Context) Error(err error)

Error stores an error in the context and aborts the current request

func (*Context) Field

func (c *Context) Field(name string) *LazyField

Field gets or creates a LazyField for the specified field name

func (*Context) File

func (c *Context) File(key string) (*multipart.FileHeader, error)

File retrieves a file from the request's multipart form.

func (*Context) FormValue

func (c *Context) FormValue(key string) string

FormValue returns the value of the specified form field.

func (*Context) Get

func (c *Context) Get(key string) (interface{}, bool)

Get retrieves a value from the context's value map.

func (*Context) GetBoolParam

func (c *Context) GetBoolParam(key string) (bool, error)

func (*Context) GetBoolParamOrDefault

func (c *Context) GetBoolParamOrDefault(key string, defaultVal bool) bool

func (*Context) GetError

func (c *Context) GetError() error

GetError retrieves the current error from the context

func (*Context) GetFloatParam

func (c *Context) GetFloatParam(key string) (float64, error)

func (*Context) GetFloatParamOrDefault

func (c *Context) GetFloatParamOrDefault(key string, defaultVal float64) float64

func (*Context) GetIntParam

func (c *Context) GetIntParam(key string) (int, error)

func (*Context) GetIntParamOrDefault

func (c *Context) GetIntParamOrDefault(key string, defaultVal int) int

func (*Context) GetParam

func (c *Context) GetParam(key string) (string, bool)

GetParam retrieves a route parameter by key, including wildcard (*).

func (*Context) GetStatus

func (c *Context) GetStatus() int

func (*Context) GetStringParamOrDefault

func (c *Context) GetStringParamOrDefault(key string, defaultVal string) string

GetStringParamOrDefault retrieves a route parameter as a string or returns the default value.

func (*Context) GetUintParam

func (c *Context) GetUintParam(key string) (uint64, error)

func (*Context) GetUintParamOrDefault

func (c *Context) GetUintParamOrDefault(key string, defaultVal uint64) uint64

func (*Context) GetValue

func (c *Context) GetValue(key string) interface{}

GetValue returns the context value only, preserving old access semantics.

func (*Context) HTML

func (c *Context) HTML(status int, html string)

HTML sends an HTML response with the specified status code.

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted checks if the request has been aborted.

func (*Context) IsWritten

func (c *Context) IsWritten() bool

func (*Context) JSON

func (c *Context) JSON(status int, data interface{})

JSON sends a JSON response with the specified status code.

func (*Context) MustParam

func (c *Context) MustParam(key string) string

MustParam retrieves a required route parameter or panics if missing or empty. This follows Go convention where Must* functions panic on failure.

func (*Context) Query

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

Query returns the value of the specified query parameter.

func (*Context) Redirect

func (c *Context) Redirect(status int, url string)

Redirect sends a redirect response to the specified URL.

func (*Context) Reset

func (c *Context) Reset(w http.ResponseWriter, r *http.Request)

func (*Context) Set

func (c *Context) Set(key string, value interface{})

func (*Context) SetCookie

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

SetCookie sets a cookie on the response with full control over all cookie properties. This is the recommended method for setting cookies with security flags (HttpOnly, Secure, SameSite).

func (*Context) SetHeader

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

SetHeader sets a header on the response writer.

func (*Context) Status

func (c *Context) Status(status int)

Status sets the response status code.

func (*Context) String

func (c *Context) String(status int, data string)

String sends a plain text response with the specified status code.

func (*Context) ValidateAllFields

func (c *Context) ValidateAllFields() bool

In lazy_validation.go, update ValidateAllFields

func (*Context) WrittenBytes

func (c *Context) WrittenBytes() int64

type ErrorMiddlewareFunc

type ErrorMiddlewareFunc func(err error, ctx *Context, next func())

type Group

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

func (*Group) Delete

func (g *Group) Delete(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Group) Get

func (g *Group) Get(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Group) Group

func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group

func (*Group) Handle

func (g *Group) Handle(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Group) Head

func (g *Group) Head(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Group) Options

func (g *Group) Options(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Group) Patch

func (g *Group) Patch(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Group) Post

func (g *Group) Post(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Group) Put

func (g *Group) Put(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Group) Use

func (g *Group) Use(middleware ...MiddlewareFunc) *Group

- middleware: The middleware functions to add

type HandlerFunc

type HandlerFunc func(*Context)

type JSONParsingConfig

type JSONParsingConfig struct {
	MaxSize        int64                 // Maximum allowed size for JSON request bodies
	ErrorHandler   func(*Context, error) // Custom error handler for parsing errors
	TargetKey      string                // Context key where parsed JSON is stored (default: "body")
	RequireJSON    bool                  // Require all requests to have application/json content type
	AllowEmptyBody bool                  // Allow empty request bodies (results in empty object)
}

JSONParsingConfig provides configuration options for the JSONParsingMiddleware

func DefaultJSONConfig

func DefaultJSONConfig() JSONParsingConfig

DefaultJSONConfig returns a default configuration for JSON parsing middleware

type LRUCache

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

LRUCache uses sharded LRUs to reduce lock contention on hot request paths.

func NewLRUCache

func NewLRUCache(capacity, maxParams int) *LRUCache

NewLRUCache creates a sharded LRU cache with the specified capacity and maxParams.

func (*LRUCache) Add

func (c *LRUCache) Add(method, path string, handler HandlerFunc, params []Param)

func (*LRUCache) Clear

func (c *LRUCache) Clear()

func (*LRUCache) Get

func (c *LRUCache) Get(method, path string) (HandlerFunc, []Param, bool)

func (*LRUCache) SetPromoteEvery

func (c *LRUCache) SetPromoteEvery(n uint32)

SetPromoteEvery configures sampled promotion frequency. Value is rounded up to next power of two and clamped to [1, 1024].

func (*LRUCache) Stats

func (c *LRUCache) Stats() (hits, misses int64, ratio float64)

type LazyField

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

LazyField represents a field that will be validated lazily

func (*LazyField) Value

func (lf *LazyField) Value() (string, *ValidationError)

Value validates and returns the field value

type MiddlewareFunc

type MiddlewareFunc func(*Context, func())

func CORSMiddleware

func CORSMiddleware(cfg *CORSConfig) MiddlewareFunc

CORSMiddleware sets CORS headers and short-circuits valid preflight requests.

func CSRFMiddleware

func CSRFMiddleware(cfg *CSRFConfig) MiddlewareFunc

CSRFMiddleware validates CSRF token on unsafe methods and sets token cookie on safe methods.

func JSONParsingMiddleware

func JSONParsingMiddleware(config *JSONParsingConfig) MiddlewareFunc

JSONParsingMiddleware creates middleware that parses JSON request bodies. It uses an optimized io.TeeReader approach to parse the body without consuming it, making it available for downstream handlers.

Parameters:

  • config: Optional configuration for the middleware. If nil, defaults are used.

Returns:

  • MiddlewareFunc: Middleware function that can be registered with the router

func RateLimitMiddleware

func RateLimitMiddleware(cfg *RateLimitConfig) MiddlewareFunc

RateLimitMiddleware applies fixed-window per-key request limiting.

func ValidationMiddleware

func ValidationMiddleware(chains ...*ValidationChain) MiddlewareFunc

type Option

type Option func(*Router)

Option configures router behavior at construction time.

func WithConfig

func WithConfig(cfg Config) Option

WithConfig replaces router configuration with a caller-provided config.

func WithPanicRecovery

func WithPanicRecovery(enabled bool) Option

WithPanicRecovery enables or disables panic recovery in ServeHTTP.

func WithRouteCacheOptions

func WithRouteCacheOptions(size, maxParams int) Option

WithRouteCacheOptions configures route cache size and max params.

func WithRouteCacheTuning

func WithRouteCacheTuning(promoteEvery uint32, minDynamicRoutes int) Option

WithRouteCacheTuning configures sampled promotion and cache activation threshold.

func WithServerMaxHeaderBytes

func WithServerMaxHeaderBytes(maxHeaderBytes int) Option

WithServerMaxHeaderBytes configures max request header size.

func WithServerTimeouts

func WithServerTimeouts(read, write, idle time.Duration) Option

WithServerTimeouts configures net/http server timeout values.

func WithTCPBufferSizes

func WithTCPBufferSizes(readBuffer, writeBuffer int) Option

WithTCPBufferSizes configures accepted TCP connection read/write buffers.

type Param

type Param struct {
	Key   string // Parameter name as defined in route pattern (e.g., ":id")
	Value string // Value extracted from request path (raw string)
}

type PathParser

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

PathParser provides zero-allocation path parsing

func NewPathParser

func NewPathParser(path string) PathParser

NewPathParser creates a new parser for the given path

func (*PathParser) Count

func (p *PathParser) Count() int

Count returns the number of path parts

func (*PathParser) IsParam

func (p *PathParser) IsParam(index int) bool

IsParam returns true if the path segment at the given index is a parameter

func (*PathParser) IsWildcard

func (p *PathParser) IsWildcard(index int) bool

IsWildcard returns true if the path segment at the given index is a wildcard

func (*PathParser) ParamName

func (p *PathParser) ParamName(index int) string

ParamName returns the parameter name at the given index

func (*PathParser) Part

func (p *PathParser) Part(index int) string

Part returns the path segment at the given index

type PathPart

type PathPart struct {
	Start int
	End   int
}

PathPart represents a single path segment with start/end indices

type RadixNode

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

RadixNode is an adaptive radix tree node optimized for HTTP routing. Static children are addressed directly by first byte for O(1) lookup.

type RateLimitConfig

type RateLimitConfig struct {
	Requests int
	Window   time.Duration

	// KeyFunc returns the bucket key for the current request.
	// Default uses best-effort client IP.
	KeyFunc func(*Context) string

	StatusCode int
	Message    string
	OnLimit    func(*Context)
}

RateLimitConfig controls opt-in request rate limiting middleware behavior.

func DefaultRateLimitConfig

func DefaultRateLimitConfig() RateLimitConfig

DefaultRateLimitConfig returns conservative default settings.

type Route

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

Route represents a registered route and provides methods for naming and configuration.

func (*Route) Name

func (rt *Route) Name(name string) *Router

Name assigns a name to this route for reverse URL generation. Returns the router to allow continued chaining of route registrations.

type RouteInfo

type RouteInfo struct {
	Method     string // HTTP method (GET, POST, etc.)
	Path       string // Route path with parameters
	HasHandler bool   // Whether the route has a handler
	Middleware int    // Number of middleware functions
}

RouteInfo contains information about a registered route

type Router

type Router struct {
	Pool sync.Pool // Exported for testing
	// contains filtered or unexported fields
}

func New

func New(opts ...Option) *Router

func (*Router) AddShutdownHook

func (r *Router) AddShutdownHook(hook ShutdownHook) *Router

func (*Router) Delete

func (r *Router) Delete(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Router) FindHandlerAndMiddleware

func (r *Router) FindHandlerAndMiddleware(method, path string) (HandlerFunc, []Param)

func (*Router) Get

func (r *Router) Get(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Router) Group

func (r *Router) Group(prefix string, middleware ...MiddlewareFunc) *Group

func (*Router) Handle

func (r *Router) Handle(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Router) Head

func (r *Router) Head(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Router) ListRoutes

func (r *Router) ListRoutes() []RouteInfo

func (*Router) MustURL

func (r *Router) MustURL(name string, params map[string]string) string

MustURL resolves a named route and panics on error.

func (*Router) MustURLWithQuery

func (r *Router) MustURLWithQuery(name string, params map[string]string, query map[string]string) string

MustURLWithQuery resolves a named route with query params and panics on error.

func (*Router) NamedRoute

func (r *Router) NamedRoute(name string) (method, path string, ok bool)

NamedRoute returns metadata for a registered named route.

func (*Router) Options

func (r *Router) Options(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Router) Patch

func (r *Router) Patch(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Router) Post

func (r *Router) Post(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Router) Put

func (r *Router) Put(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*Router) ServeHTTP

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

func (*Router) ServeStatic

func (r *Router) ServeStatic(prefix, root string) *Router

func (*Router) SetPanicRecovery

func (r *Router) SetPanicRecovery(enabled bool)

SetPanicRecovery controls whether ServeHTTP recovers panics and returns 500s. Disabling recovery removes defer/recover overhead from the hot path.

func (*Router) SetRouteCacheOptions

func (r *Router) SetRouteCacheOptions(size, maxParams int)

func (*Router) SetRouteCacheTuning

func (r *Router) SetRouteCacheTuning(promoteEvery, minDynamicRoutes int)

SetRouteCacheTuning adjusts cache behavior for hit-path contention and usefulness. promoteEvery controls sampled hit promotion frequency. minDynamicRoutes controls minimum dynamic routes per method before cache is used.

func (*Router) Shutdown

func (r *Router) Shutdown(timeout time.Duration) error

func (*Router) ShutdownImmediate

func (r *Router) ShutdownImmediate() error

func (*Router) Start

func (r *Router) Start(port string) error

func (*Router) StartTLS

func (r *Router) StartTLS(port, certFile, keyFile string) error

func (*Router) URL

func (r *Router) URL(name string, params map[string]string) (string, error)

URL resolves a named route into a concrete path. params keys should match route placeholders (":id" => "id", "*path" => "path").

func (*Router) URLWithQuery

func (r *Router) URLWithQuery(name string, params map[string]string, query map[string]string) (string, error)

URLWithQuery resolves a named route and appends encoded query parameters.

func (*Router) Use

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

func (*Router) UseError

func (r *Router) UseError(middleware ...ErrorMiddlewareFunc) *Router

type RouterGroup

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

func (*RouterGroup) Delete

func (g *RouterGroup) Delete(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*RouterGroup) Get

func (g *RouterGroup) Get(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*RouterGroup) Post

func (g *RouterGroup) Post(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*RouterGroup) Put

func (g *RouterGroup) Put(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

func (*RouterGroup) Use

func (g *RouterGroup) Use(middleware ...MiddlewareFunc) *RouterGroup

type ShutdownHook

type ShutdownHook func() error

type TrackedResponseWriter

type TrackedResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

TrackedResponseWriter wraps http.ResponseWriter to track if headers have been sent.

func WrapResponseWriter

func WrapResponseWriter(w http.ResponseWriter) *TrackedResponseWriter

WrapResponseWriter creates a new TrackedResponseWriter.

func (*TrackedResponseWriter) BytesWritten

func (w *TrackedResponseWriter) BytesWritten() int64

BytesWritten returns the number of bytes written.

func (*TrackedResponseWriter) Flush

func (w *TrackedResponseWriter) Flush()

Flush implements http.Flusher interface if the underlying writer supports it.

func (*TrackedResponseWriter) Hijack

Hijack implements http.Hijacker interface if the underlying writer supports it.

func (*TrackedResponseWriter) Push

func (w *TrackedResponseWriter) Push(target string, opts *http.PushOptions) error

Push implements http.Pusher interface if the underlying writer supports it.

func (*TrackedResponseWriter) Status

func (w *TrackedResponseWriter) Status() int

Status returns the HTTP status code that was set.

func (*TrackedResponseWriter) Unwrap

Unwrap returns the original ResponseWriter.

func (*TrackedResponseWriter) Write

func (w *TrackedResponseWriter) Write(b []byte) (int, error)

Write records that data (and implicitly headers) have been written.

func (*TrackedResponseWriter) WriteHeader

func (w *TrackedResponseWriter) WriteHeader(statusCode int)

WriteHeader records that headers have been written.

func (*TrackedResponseWriter) Written

func (w *TrackedResponseWriter) Written() bool

Written returns whether headers have been sent.

type ValidationChain

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

ValidationChain represents a chain of validation rules for a field.

func NewValidationChain

func NewValidationChain(field string) *ValidationChain

NewValidationChain creates a new ValidationChain for the specified field.

func (*ValidationChain) Custom

func (vc *ValidationChain) Custom(fn func(string) error) *ValidationChain

Custom adds a custom validation function to the chain.

func (*ValidationChain) IsArray

func (vc *ValidationChain) IsArray() *ValidationChain

IsArray adds a rule that the field must be a JSON array.

func (*ValidationChain) IsBoolean

func (vc *ValidationChain) IsBoolean() *ValidationChain

IsBoolean adds a rule that the field must be a boolean value.

func (*ValidationChain) IsEmail

func (vc *ValidationChain) IsEmail() *ValidationChain

IsEmail adds a rule that the field must be a valid email address.

func (*ValidationChain) IsFloat

func (vc *ValidationChain) IsFloat() *ValidationChain

IsFloat adds a rule that the field must be a floating-point number.

func (*ValidationChain) IsInt

func (vc *ValidationChain) IsInt() *ValidationChain

IsInt adds a rule that the field must be an integer.

func (*ValidationChain) IsObject

func (vc *ValidationChain) IsObject() *ValidationChain

IsObject adds a rule that the field must be a JSON object.

func (*ValidationChain) Length

func (vc *ValidationChain) Length(min, maxLength int) *ValidationChain

Length adds a rule that the field must have a length within specified range

func (*ValidationChain) Matches

func (vc *ValidationChain) Matches(pattern string) *ValidationChain

Matches adds a rule that the field must match the specified regular expression.

func (*ValidationChain) Max

func (vc *ValidationChain) Max(max int) *ValidationChain

Max adds a rule that the field must be at most a specified integer value.

func (*ValidationChain) Min

func (vc *ValidationChain) Min(min int) *ValidationChain

Min adds a rule that the field must be at least a specified integer value.

func (*ValidationChain) OneOf

func (vc *ValidationChain) OneOf(options ...string) *ValidationChain

OneOf adds a rule that the field must be one of the specified options.

func (*ValidationChain) Release

func (vc *ValidationChain) Release()

Release returns the ValidationChain to the pool

func (*ValidationChain) Required

func (vc *ValidationChain) Required() *ValidationChain

Required adds a rule that the field must not be empty.

type ValidationError

type ValidationError struct {
	Field string `json:"field"` // Field name that failed validation
	Err   string `json:"error"` // Error message describing the failure
}

ValidationError represents a single validation error with field and message.

func (*ValidationError) Error

func (ve *ValidationError) Error() string

Error implements the error interface.

type ValidationErrors

type ValidationErrors []ValidationError

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

type ValidatorFunc

type ValidatorFunc func(string) *ValidationError

ValidatorFunc defines the signature for validation functions. It validates a string value and returns a pre-allocated ValidationError object.

Directories

Path Synopsis
benchmark
cmd/wrk_server command
quic module

Jump to

Keyboard shortcuts

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