Router Options
3 minute read
Router options are passed to router.New() or router.MustNew() to configure the router.
Router Creation
// With error handling
r, err := router.New(opts...)
if err != nil {
log.Fatalf("Failed to create router: %v", err)
}
// Panics on invalid configuration. Use at startup.
r := router.MustNew(opts...)
Versioning Options
WithVersioning(opts ...version.Option)
Configures API versioning support using functional options from the version package.
import "rivaas.dev/router/version"
r := router.MustNew(
router.WithVersioning(
version.WithHeaderDetection("X-API-Version"),
version.WithDefault("v1"),
),
)
With multiple detection strategies:
r := router.MustNew(
router.WithVersioning(
version.WithPathDetection("/api/v{version}"),
version.WithHeaderDetection("X-API-Version"),
version.WithQueryDetection("v"),
version.WithDefault("v2"),
version.WithResponseHeaders(),
version.WithSunsetEnforcement(),
),
)
Diagnostic Options
WithDiagnostics(handler DiagnosticHandler)
Sets a diagnostic handler for informational events like header injection attempts or configuration warnings.
import "log/slog"
handler := router.DiagnosticHandlerFunc(func(e router.DiagnosticEvent) {
slog.Warn(e.Message, "kind", e.Kind, "fields", e.Fields)
})
r := router.MustNew(router.WithDiagnostics(handler))
With metrics:
handler := router.DiagnosticHandlerFunc(func(e router.DiagnosticEvent) {
metrics.Increment("router.diagnostics", "kind", string(e.Kind))
})
Server Options
WithH2C(enable bool)
Enables HTTP/2 Cleartext (h2c) support.
Only use in development or behind a trusted load balancer. DO NOT enable on public-facing servers without TLS.
r := router.MustNew(router.WithH2C(true))
WithServerTimeouts(opts ...ServerTimeoutOption)
Configures HTTP server timeouts using functional options. Pass one or more of: WithReadHeaderTimeout, WithReadTimeout, WithWriteTimeout, WithIdleTimeout. Options not set keep their defaults.
Defaults (if not set):
- ReadHeaderTimeout: 5s
- ReadTimeout: 15s
- WriteTimeout: 30s
- IdleTimeout: 60s
// Override all four
r := router.MustNew(router.WithServerTimeouts(
router.WithReadHeaderTimeout(5*time.Second),
router.WithReadTimeout(20*time.Second),
router.WithWriteTimeout(60*time.Second),
router.WithIdleTimeout(120*time.Second),
))
// Override only what you need
r := router.MustNew(router.WithServerTimeouts(
router.WithReadTimeout(30*time.Second),
))
Performance Options
WithRouteCompilation(enabled bool)
Turns compiled route matching on or off. By default it’s off: the router uses tree traversal, which is fast and works well for most apps. Turn it on when you have a lot of routes (for example hundreds of static routes). Then the router can use pre-compiled lookups and bloom filters to speed things up.
Default: false (tree traversal)
// Default: tree traversal (no need to set anything)
r := router.MustNew()
// Turn on compiled routes for large APIs
r := router.MustNew(router.WithRouteCompilation(true))
WithBloomFilterSize(size uint64)
Sets the bloom filter size when you use compiled routes. Larger sizes reduce false positives.
Default: 1000
Recommended: 2-3x the number of static routes
r := router.MustNew(router.WithBloomFilterSize(2000)) // For ~1000 routes
WithBloomFilterHashFunctions(numFuncs int)
Sets the number of hash functions for bloom filters.
Default: 3
Range: 1-10 (clamped)
r := router.MustNew(router.WithBloomFilterHashFunctions(4))
WithoutCancellationCheck()
Disables context cancellation checking in the middleware chain. Cancellation checking is enabled by default: the router checks for canceled contexts between handlers to avoid wasted work on timed-out requests.
Use when you don’t use request timeouts, handle cancellation manually in handlers, or want to avoid the small overhead of cancellation checks.
// Default: cancellation check enabled (no option needed)
r := router.MustNew()
// Disable if you handle cancellation manually
r := router.MustNew(router.WithoutCancellationCheck())
Complete Example
package main
import (
"log/slog"
"net/http"
"os"
"time"
"rivaas.dev/router"
"rivaas.dev/router/version"
)
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
// Diagnostic handler
diagHandler := router.DiagnosticHandlerFunc(func(e router.DiagnosticEvent) {
logger.Warn(e.Message, "kind", e.Kind, "fields", e.Fields)
})
// Create router with options
r := router.MustNew(
// Versioning
router.WithVersioning(
version.WithHeaderDetection("API-Version"),
version.WithDefault("v1"),
),
// Server configuration
router.WithServerTimeouts(
router.WithReadHeaderTimeout(5*time.Second),
router.WithReadTimeout(20*time.Second),
router.WithWriteTimeout(60*time.Second),
router.WithIdleTimeout(120*time.Second),
),
// Performance tuning
router.WithBloomFilterSize(2000),
// Diagnostics
router.WithDiagnostics(diagHandler),
)
r.GET("/", func(c *router.Context) {
c.JSON(200, map[string]string{"message": "Hello"})
})
http.ListenAndServe(":8080", r)
}
Observability Options
For tracing, metrics, and logging configuration, use the app package which provides WithObservability(), WithTracing(), WithMetrics(), and WithLogging() options. These options configure the full observability stack and integrate with the router automatically.
import (
"rivaas.dev/app"
"rivaas.dev/tracing"
"rivaas.dev/metrics"
)
application := app.New(
app.WithServiceName("my-api"),
app.WithObservability(
app.WithTracing(tracing.WithSampleRate(0.1)),
app.WithMetrics(metrics.WithPrometheus()),
app.WithExcludePaths("/health", "/metrics"),
),
)
Next Steps
- API Reference: See core types and methods
- Diagnostics: Learn about diagnostic events
- Context API: Check Context methods
- App Package: See app observability options
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.