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
- func ParseRateLimitRequests(raw string, fallback int) int
- func ParseRateLimitWindow(raw string, fallback time.Duration) time.Duration
- type BufferedResponseWriter
- type CORSConfig
- type CSRFConfig
- type Config
- type Context
- func (c *Context) Abort()
- func (c *Context) Bind(v interface{}) error
- func (c *Context) CheckValidation() bool
- func (c *Context) CleanupPooledResources()
- func (c *Context) ClearLazyFields()
- func (c *Context) ClearValues()
- func (c *Context) Cookie(name, value string, options ...interface{})
- func (c *Context) Error(err error)
- func (c *Context) Field(name string) *LazyField
- func (c *Context) File(key string) (*multipart.FileHeader, error)
- func (c *Context) FormValue(key string) string
- func (c *Context) Get(key string) (interface{}, bool)
- func (c *Context) GetBoolParam(key string) (bool, error)
- func (c *Context) GetBoolParamOrDefault(key string, defaultVal bool) bool
- func (c *Context) GetError() error
- func (c *Context) GetFloatParam(key string) (float64, error)
- func (c *Context) GetFloatParamOrDefault(key string, defaultVal float64) float64
- func (c *Context) GetIntParam(key string) (int, error)
- func (c *Context) GetIntParamOrDefault(key string, defaultVal int) int
- func (c *Context) GetParam(key string) (string, bool)
- func (c *Context) GetStatus() int
- func (c *Context) GetStringParamOrDefault(key string, defaultVal string) string
- func (c *Context) GetUintParam(key string) (uint64, error)
- func (c *Context) GetUintParamOrDefault(key string, defaultVal uint64) uint64
- func (c *Context) GetValue(key string) interface{}
- func (c *Context) HTML(status int, html string)
- func (c *Context) IsAborted() bool
- func (c *Context) IsWritten() bool
- func (c *Context) JSON(status int, data interface{})
- func (c *Context) MustParam(key string) string
- func (c *Context) Query(key string) string
- func (c *Context) Redirect(status int, url string)
- func (c *Context) Reset(w http.ResponseWriter, r *http.Request)
- func (c *Context) Set(key string, value interface{})
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) Status(status int)
- func (c *Context) String(status int, data string)
- func (c *Context) ValidateAllFields() bool
- func (c *Context) WrittenBytes() int64
- type ErrorMiddlewareFunc
- type Group
- func (g *Group) Delete(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *Group) Get(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group
- func (g *Group) Handle(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *Group) Head(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *Group) Options(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *Group) Patch(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *Group) Post(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *Group) Put(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *Group) Use(middleware ...MiddlewareFunc) *Group
- type HandlerFunc
- type JSONParsingConfig
- type LRUCache
- type LazyField
- type MiddlewareFunc
- func CORSMiddleware(cfg *CORSConfig) MiddlewareFunc
- func CSRFMiddleware(cfg *CSRFConfig) MiddlewareFunc
- func JSONParsingMiddleware(config *JSONParsingConfig) MiddlewareFunc
- func RateLimitMiddleware(cfg *RateLimitConfig) MiddlewareFunc
- func ValidationMiddleware(chains ...*ValidationChain) MiddlewareFunc
- type Option
- func WithConfig(cfg Config) Option
- func WithPanicRecovery(enabled bool) Option
- func WithRouteCacheOptions(size, maxParams int) Option
- func WithRouteCacheTuning(promoteEvery uint32, minDynamicRoutes int) Option
- func WithServerMaxHeaderBytes(maxHeaderBytes int) Option
- func WithServerTimeouts(read, write, idle time.Duration) Option
- func WithTCPBufferSizes(readBuffer, writeBuffer int) Option
- type Param
- type PathParser
- type PathPart
- type RadixNode
- type RateLimitConfig
- type Route
- type RouteInfo
- type Router
- func (r *Router) AddShutdownHook(hook ShutdownHook) *Router
- func (r *Router) Delete(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (r *Router) FindHandlerAndMiddleware(method, path string) (HandlerFunc, []Param)
- func (r *Router) Get(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (r *Router) Group(prefix string, middleware ...MiddlewareFunc) *Group
- func (r *Router) Handle(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (r *Router) Head(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (r *Router) ListRoutes() []RouteInfo
- func (r *Router) MustURL(name string, params map[string]string) string
- func (r *Router) MustURLWithQuery(name string, params map[string]string, query map[string]string) string
- func (r *Router) NamedRoute(name string) (method, path string, ok bool)
- func (r *Router) Options(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (r *Router) Patch(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (r *Router) Post(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (r *Router) Put(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) ServeStatic(prefix, root string) *Router
- func (r *Router) SetPanicRecovery(enabled bool)
- func (r *Router) SetRouteCacheOptions(size, maxParams int)
- func (r *Router) SetRouteCacheTuning(promoteEvery, minDynamicRoutes int)
- func (r *Router) Shutdown(timeout time.Duration) error
- func (r *Router) ShutdownImmediate() error
- func (r *Router) Start(port string) error
- func (r *Router) StartTLS(port, certFile, keyFile string) error
- func (r *Router) URL(name string, params map[string]string) (string, error)
- func (r *Router) URLWithQuery(name string, params map[string]string, query map[string]string) (string, error)
- func (r *Router) Use(middleware ...MiddlewareFunc)
- func (r *Router) UseError(middleware ...ErrorMiddlewareFunc) *Router
- type RouterGroup
- func (g *RouterGroup) Delete(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *RouterGroup) Get(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *RouterGroup) Post(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *RouterGroup) Put(path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route
- func (g *RouterGroup) Use(middleware ...MiddlewareFunc) *RouterGroup
- type ShutdownHook
- type TrackedResponseWriter
- func (w *TrackedResponseWriter) BytesWritten() int64
- func (w *TrackedResponseWriter) Flush()
- func (w *TrackedResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *TrackedResponseWriter) Push(target string, opts *http.PushOptions) error
- func (w *TrackedResponseWriter) Status() int
- func (w *TrackedResponseWriter) Unwrap() http.ResponseWriter
- func (w *TrackedResponseWriter) Write(b []byte) (int, error)
- func (w *TrackedResponseWriter) WriteHeader(statusCode int)
- func (w *TrackedResponseWriter) Written() bool
- type ValidationChain
- func (vc *ValidationChain) Custom(fn func(string) error) *ValidationChain
- func (vc *ValidationChain) IsArray() *ValidationChain
- func (vc *ValidationChain) IsBoolean() *ValidationChain
- func (vc *ValidationChain) IsEmail() *ValidationChain
- func (vc *ValidationChain) IsFloat() *ValidationChain
- func (vc *ValidationChain) IsInt() *ValidationChain
- func (vc *ValidationChain) IsObject() *ValidationChain
- func (vc *ValidationChain) Length(min, maxLength int) *ValidationChain
- func (vc *ValidationChain) Matches(pattern string) *ValidationChain
- func (vc *ValidationChain) Max(max int) *ValidationChain
- func (vc *ValidationChain) Min(min int) *ValidationChain
- func (vc *ValidationChain) OneOf(options ...string) *ValidationChain
- func (vc *ValidationChain) Release()
- func (vc *ValidationChain) Required() *ValidationChain
- type ValidationError
- type ValidationErrors
- type ValidatorFunc
Constants ¶
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 ¶
ParseRateLimitRequests parses request limits from string config values.
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
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) CheckValidation ¶
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) File ¶
func (c *Context) File(key string) (*multipart.FileHeader, error)
File retrieves a file from the request's multipart form.
func (*Context) GetBoolParamOrDefault ¶
func (*Context) GetFloatParamOrDefault ¶
func (*Context) GetIntParamOrDefault ¶
func (*Context) GetStringParamOrDefault ¶
GetStringParamOrDefault retrieves a route parameter as a string or returns the default value.
func (*Context) GetUintParamOrDefault ¶
func (*Context) GetValue ¶
GetValue returns the context value only, preserving old access semantics.
func (*Context) MustParam ¶
MustParam retrieves a required route parameter or panics if missing or empty. This follows Go convention where Must* functions panic on failure.
func (*Context) SetCookie ¶
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) ValidateAllFields ¶
In lazy_validation.go, update ValidateAllFields
func (*Context) WrittenBytes ¶
type ErrorMiddlewareFunc ¶
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) 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 ¶
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) SetPromoteEvery ¶
SetPromoteEvery configures sampled promotion frequency. Value is rounded up to next power of two and clamped to [1, 1024].
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 ¶
WithConfig replaces router configuration with a caller-provided config.
func WithPanicRecovery ¶
WithPanicRecovery enables or disables panic recovery in ServeHTTP.
func WithRouteCacheOptions ¶
WithRouteCacheOptions configures route cache size and max params.
func WithRouteCacheTuning ¶
WithRouteCacheTuning configures sampled promotion and cache activation threshold.
func WithServerMaxHeaderBytes ¶
WithServerMaxHeaderBytes configures max request header size.
func WithServerTimeouts ¶
WithServerTimeouts configures net/http server timeout values.
func WithTCPBufferSizes ¶
WithTCPBufferSizes configures accepted TCP connection read/write buffers.
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) 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 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.
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 (*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) 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 (*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 ¶
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) ServeStatic ¶
func (*Router) SetPanicRecovery ¶
SetPanicRecovery controls whether ServeHTTP recovers panics and returns 500s. Disabling recovery removes defer/recover overhead from the hot path.
func (*Router) SetRouteCacheOptions ¶
func (*Router) SetRouteCacheTuning ¶
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) ShutdownImmediate ¶
func (*Router) URL ¶
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 ¶
func (w *TrackedResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
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 ¶
func (w *TrackedResponseWriter) Unwrap() http.ResponseWriter
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.