HTTP Router
5 minute read
The Rivaas Router provides a high-performance routing system. Includes built-in middleware, OpenTelemetry support, and complete request handling.
Overview
The Rivaas Router is a production-ready HTTP router for cloud-native applications. It combines high performance with a rich feature set. It offers sub-microsecond routing and high throughput. See Router Performance for current benchmark numbers. It includes content negotiation, API versioning, and OpenTelemetry support.
Key Features
Core Routing & Request Handling
- Radix tree routing - Path matching with bloom filters for static route lookups.
- Optional compiled route tables - For large APIs you can turn on pre-compiled routes to speed up lookups.
- Path Parameters:
/users/:id,/posts/:id/:action- Array-based storage for route parameters. - Wildcard Routes:
/files/*filepath- Catch-all routing for file serving. - Route Groups: Organize routes with shared prefixes and middleware.
- Middleware Chain: Global, group-level, and route-level middleware support.
- Route Constraints: Numeric, UUID, Alpha, Alphanumeric, Custom regex validation.
- Concurrent Safe: Thread-safe for use by multiple goroutines.
Works with: Request Binding
The router works well with the binding package. Use it to parse request data into structs:
- Binding Package: Full binding with
binding.Query(),binding.JSON(),binding.Form(),binding.Headers(),binding.Cookies(). - App Package: Integrated binding + validation with
app.Bind[T](),app.BindStrict[T](). - 15+ Type Categories: Primitives, Time, Network types like net.IP and net.IPNet, Maps, Nested Structs, Slices.
- Advanced Features: Maps with dot or bracket notation, nested structs in query strings, enum validation, default values.
Works with: Request Validation
The validation package offers multiple strategies you can use after binding:
- Multiple Strategies: Interface validation, Tag validation with go-playground/validator, JSON Schema.
- Partial Validation: PATCH request support. Validate only present fields.
- Structured Errors: Machine-readable error codes and field paths.
- Context-Aware: Request-scoped validation rules.
Response Rendering
- JSON Variants: Standard, Indented, Pure, Secure, ASCII, JSONP.
- Alternative Formats: YAML, String, HTML.
- Binary & Streaming: Zero-copy streaming from io.Reader, file serving.
Content Negotiation - RFC 7231 Compliant
- Media type negotiation with quality values.
- Character set, encoding, and language negotiation.
- Wildcard support and specificity matching.
API Versioning - Built-in
- Header-based:
API-Version: v1 - Query-based:
?version=v1 - Custom detection: Flexible version strategies
- Version-specific routes:
r.Version("v1").GET(...) - Lock-free implementation: Atomic operations
Middleware (Built-in)
- AccessLog - Structured HTTP access logging
- Recovery - Panic recovery with graceful errors
- CORS - Cross-Origin Resource Sharing
- Basic Auth - HTTP Basic Authentication
- Compression - Gzip/Brotli response compression
- Request ID - X-Request-ID generation
- Security Headers - HSTS, CSP, X-Frame-Options
- Timeout - Request timeout handling
- Rate Limit - Token bucket rate limiting
- Body Limit - Request body size limiting
Observability - OpenTelemetry
- Metrics: Custom histograms, counters, gauges, automatic request metrics
- Tracing: OpenTelemetry support via recorder interface; zero overhead when disabled
- Diagnostics: Optional diagnostic events for security concerns
Performance
- Sub-microsecond routing and high throughput — See Router Performance for current latency and throughput numbers.
- Zero allocation — 0 allocs for routing and parameter extraction in the benchmarked scenarios (static, 1 param, 2 params). One small allocation only when a route has more than 8 path parameters.
- Memory efficient — Context pooling and minimal allocations per request.
- Context pooling: Automatic context reuse
- Lock-free operations: Atomic operations for concurrent access
Quick Start
Get up and running in minutes with this complete example:
package main
import (
"fmt"
"net/http"
"time"
"rivaas.dev/router"
)
func main() {
r := router.MustNew() // Panics on invalid config (use at startup)
// Global middleware
r.Use(Logger(), Recovery())
// Simple route
r.GET("/", func(c *router.Context) {
c.JSON(http.StatusOK, map[string]string{
"message": "Hello Rivaas!",
"version": "1.0.0",
})
})
// Parameter route
r.GET("/users/:id", func(c *router.Context) {
userID := c.Param("id")
c.JSON(http.StatusOK, map[string]string{
"user_id": userID,
})
})
// POST with JSON binding
r.POST("/users", func(c *router.Context) {
var req struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := json.NewDecoder(c.Request.Body).Decode(&req); err != nil {
c.WriteErrorResponse(http.StatusBadRequest, "Invalid JSON")
return
}
c.JSON(http.StatusCreated, req)
})
http.ListenAndServe(":8080", r)
}
// Middleware examples
func Logger() router.HandlerFunc {
return func(c *router.Context) {
start := time.Now()
c.Next()
duration := time.Since(start)
fmt.Printf("[%s] %s - %v\n", c.Request.Method, c.Request.URL.Path, duration)
}
}
func Recovery() router.HandlerFunc {
return func(c *router.Context) {
defer func() {
if err := recover(); err != nil {
c.JSON(http.StatusInternalServerError, map[string]string{
"error": "Internal server error",
})
}
}()
c.Next()
}
}
Learning Path
Follow this structured path to master the Rivaas Router:
1. Getting Started
Start with the basics:
- Installation - Set up the router in your project
- Basic Usage - Create your first router and routes
- Route Patterns - Learn about static, parameter, and wildcard routes
2. Core Features
Build upon the fundamentals:
- Route Groups - Organize routes with groups and prefixes
- Middleware - Add cross-cutting concerns like logging and auth
- Context - Understand the request context and memory safety
3. Request Handling
Handle requests effectively:
- Request Binding - Automatically parse request data to structs
- Validation - Validate requests with multiple strategies
- Response Rendering - Render JSON, YAML, HTML, and binary responses
4. Advanced Features
Use advanced capabilities:
- Content Negotiation - Handle Accept headers and format negotiation
- API Versioning - Build versioned APIs with built-in support
- Static Files - Serve static files and directories
5. Production Readiness
Prepare for production:
- Observability - Integrate OpenTelemetry tracing and diagnostics
- Testing - Test your routes and middleware
- Migration - Migrate from Gin, Echo, or http.ServeMux
6. Examples & Patterns
Learn from real-world examples:
- Examples - Complete working examples and use cases
Common Use Cases
The Rivaas Router excels in these scenarios:
- REST APIs - JSON APIs with comprehensive request/response handling
- Web Applications - HTML rendering, forms, sessions, static files
- Microservices - OpenTelemetry integration, API versioning, health checks
- High-Performance Services - Sub-microsecond routing and high throughput
Next Steps
- Installation: Install the router and set up your first project
- Basic Usage: Follow the Basic Usage guide to learn the fundamentals
- Examples: Explore complete examples for common patterns
- API Reference: Check the API Reference for detailed documentation
Need Help?
- Troubleshooting: See Common Issues
- Examples: Browse working examples
- API Docs: Check pkg.go.dev
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.