pub struct ServerBuilder { /* private fields */ }Implementations§
Source§impl ServerBuilder
impl ServerBuilder
pub fn create(host: &str, port: u16, setup: FoxtiveSetup) -> ServerBuilder
pub fn app(self, app: &str) -> Self
pub fn tracing(self, config: Tracing) -> Self
Sourcepub fn workers(self, workers: usize) -> Self
pub fn workers(self, workers: usize) -> Self
Set number of workers to start.
By default http server uses 2
Sourcepub fn backlog(self, backlog: i32) -> Self
pub fn backlog(self, backlog: i32) -> Self
Set the maximum number of pending connections.
This refers to the number of clients that can be waiting to be served. Exceeding this number results in the client getting an error when attempting to connect. It should only affect servers under significant load.
Generally set in the 64-2048 range. Default value is 2048.
This method should be called before bind() method call.
Sourcepub fn keep_alive(self, keep_alive: Seconds) -> Self
pub fn keep_alive(self, keep_alive: Seconds) -> Self
Set server keep-alive setting.
By default keep alive is set to a 5 seconds.
Sourcepub fn client_timeout(self, timeout: u16) -> Self
pub fn client_timeout(self, timeout: u16) -> Self
Set request read timeout in seconds.
Defines a timeout for reading client request headers. If a client does not transmit the entire set headers within this time, the request is terminated with the 408 (Request Time-out) error.
To disable timeout set value to 0.
By default client timeout is set to 3 seconds.
Sourcepub fn client_disconnect(self, timeout: u16) -> Self
pub fn client_disconnect(self, timeout: u16) -> Self
Set server connection disconnect timeout in seconds.
Defines a timeout for shutdown connection. If a shutdown procedure does not complete within this time, the request is dropped.
To disable timeout set value to 0.
By default client timeout is set to 5 seconds.
Sourcepub fn max_conn(self, max: usize) -> Self
pub fn max_conn(self, max: usize) -> Self
Sets the maximum per-worker number of concurrent connections.
All socket listeners will stop accepting connections when this limit is reached for each worker.
By default max connections is set to a 25k.
Sourcepub fn max_conn_rate(self, max: usize) -> Self
pub fn max_conn_rate(self, max: usize) -> Self
Sets the maximum per-worker concurrent connection establish process.
All listeners will stop accepting connections when this limit is reached. It can be used to limit the global SSL CPU usage.
By default max connections is set to a 256.
pub fn allowed_origins(self, allowed_origins: Vec<String>) -> Self
pub fn allowed_methods(self, allowed_methods: Vec<Method>) -> Self
Sourcepub fn route_factory<F: Fn() -> Vec<Route> + Send + Sync + 'static>(
self,
factory: F,
) -> Self
pub fn route_factory<F: Fn() -> Vec<Route> + Send + Sync + 'static>( self, factory: F, ) -> Self
Set the route factory function.
This function is called once per worker to create route definitions.
Sourcepub fn route_factory_arc(
self,
factory: Arc<dyn Fn() -> Vec<Route> + Send + Sync>,
) -> Self
pub fn route_factory_arc( self, factory: Arc<dyn Fn() -> Vec<Route> + Send + Sync>, ) -> Self
Set the route factory using an existing Arc.
Useful for sharing the same factory across multiple server configurations.
pub fn boot_thread<F: Fn() -> Vec<Route> + Send + Sync + 'static>( self, factory: F, ) -> Self
Use route_factory instead
pub fn has_started_bootstrap(self, has_started_bootstrap: bool) -> Self
pub fn body_config(self, body_config: BodyConfig) -> Self
pub fn json_config(self, config: BodyConfig) -> Self
Use body_config instead
pub fn custom_state_builder( self, builder: Box<dyn FnOnce() -> HashMap<String, Box<dyn Any + Send + Sync>> + Send>, ) -> Self
Sourcepub fn on_shutdown<F>(self, func: F) -> Self
pub fn on_shutdown<F>(self, func: F) -> Self
Sets a custom shutdown handler to be called when the application is shutting down.
This method allows you to provide a future that will be awaited during shutdown. It is typically used to perform cleanup tasks like closing database connections, flushing logs, or other async teardown operations.
Note: If a custom shutdown_signal is also provided using [shutdown_signal],
that will take precedence over this handler, and this on_shutdown handler will
not be executed.
Sourcepub fn shutdown_signal<F>(self, func: F) -> Self
pub fn shutdown_signal<F>(self, func: F) -> Self
Sets a custom shutdown signal handler that determines when the application should begin shutting down.
This method allows you to provide a future that, when resolved, triggers the application shutdown.
It is typically used to listen for signals like Ctrl+C or system termination requests (SIGTERM).
If this shutdown signal is provided, it will override any handler set using [on_shutdown].
Sourcepub fn validate(&self) -> AppResult<()>
pub fn validate(&self) -> AppResult<()>
Validate the server configuration before startup.
This method checks for common configuration errors and warns about potentially problematic settings. It returns an error if critical issues are found.
§Validation Rules
- Port must not be 0
- Workers must be at least 1
- Backlog must not be negative
- Timeout values are checked for reasonable ranges (warnings only)
§Example
use foxtive_ntex::http::server::ServerConfig;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::validate_example();Sourcepub fn dev_mode(host: &str, port: u16, setup: FoxtiveSetup) -> Self
pub fn dev_mode(host: &str, port: u16, setup: FoxtiveSetup) -> Self
Create a server configuration with smart defaults for development.
This is a convenience method that creates a configuration optimized for local development with relaxed timeouts and single worker.
§Defaults
- Workers: 1 (easier debugging)
- Client timeout: 60 seconds
- Keep-alive: 60 seconds
- Max connections: 1000
- Backlog: 256
§Example
use foxtive_ntex::http::server::ServerConfig;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::dev_mode("127.0.0.1", 3000, setup);Sourcepub fn production_mode(host: &str, port: u16, setup: FoxtiveSetup) -> Self
pub fn production_mode(host: &str, port: u16, setup: FoxtiveSetup) -> Self
Create a server configuration optimized for production deployment.
This configuration uses conservative settings suitable for most production workloads with good performance and resource management.
§Defaults
- Workers: Auto-detected (number of CPU cores)
- Client timeout: 15 seconds
- Keep-alive: 30 seconds
- Max connections: 25,000
- Backlog: 2048
§Example
use foxtive_ntex::http::server::ServerConfig;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::production_mode("0.0.0.0", 8080, setup);Sourcepub fn high_performance_mode(host: &str, port: u16, setup: FoxtiveSetup) -> Self
pub fn high_performance_mode(host: &str, port: u16, setup: FoxtiveSetup) -> Self
Create a server configuration optimized for high-performance scenarios.
This configuration maximizes throughput and concurrent connections, suitable for high-traffic APIs or microservices.
§Defaults
- Workers: 2x CPU cores (for I/O-bound workloads)
- Client timeout: 5 seconds
- Keep-alive: 10 seconds
- Max connections: 50,000
- Max connection rate: 512
- Backlog: 4096
§Warning
This configuration uses more resources. Monitor your system to ensure it can handle the increased load.
§Example
use foxtive_ntex::http::server::ServerConfig;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::high_performance_mode("0.0.0.0", 8080, setup);Sourcepub fn shutdown_config(self, config: ShutdownConfig) -> Self
pub fn shutdown_config(self, config: ShutdownConfig) -> Self
Configure shutdown behavior with timeout and cleanup coordination.
This method sets up coordinated shutdown for all registered services. Services are shut down in priority order with per-service timeouts.
§Arguments
config- Shutdown configuration with timeout settings
§Example
use foxtive_ntex::http::server::{ServerConfig, ShutdownConfig};
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerConfig::create("127.0.0.1", 8080, setup)
// .shutdown_config(ShutdownConfig::new(30));Sourcepub fn register_shutdown_service<F, Fut>(
self,
name: &str,
priority: u8,
cleanup: F,
) -> Self
pub fn register_shutdown_service<F, Fut>( self, name: &str, priority: u8, cleanup: F, ) -> Self
Register a service for graceful shutdown cleanup.
Services are shut down in priority order (lower priority number first). Each service has a timeout to prevent one slow service from blocking others.
§Arguments
name- Name of the service (for logging)priority- Shutdown priority (lower = shutdown first)- 0-10: Critical infrastructure (databases, message queues)
- 11-50: Application services (caches, connection pools)
- 51-100: Auxiliary services (loggers, metrics)
cleanup- Async cleanup function to execute
§Example
use foxtive_ntex::http::server::ServerBuilder;
// FoxtiveSetup must be created with your application's setup logic
// let config = ServerBuilder::create("127.0.0.1", 8080, setup)
// .register_shutdown_service("database", 1, || async {
// println!("Database closed");
// });Sourcepub async fn start<Callback, Fut>(self, callback: Callback) -> AppResult<()>
pub async fn start<Callback, Fut>(self, callback: Callback) -> AppResult<()>
Start the HTTP server with an optional bootstrap callback.
This method validates the configuration, sets up the ntex server, and starts listening for incoming requests.
§Arguments
callback- Optional async function that runs after state creation but before server starts. Useful for database migrations, cache warming, etc.
§Example
use foxtive_ntex::http::server::ServerBuilder;
use foxtive::setup::FoxtiveSetup;
let foxtive = FoxtiveSetup::default();
ServerBuilder::dev_mode("127.0.0.1", 3000, foxtive)
.on_shutdown(async {
println!("Server shutting down gracefully");
})
.start(|state| async move {
// Bootstrap code here (e.g., database migrations)
println!("Server starting...");
Ok(())
})
.await?;Sourcepub async fn run(self) -> AppResult<()>
pub async fn run(self) -> AppResult<()>
Start the HTTP server without a bootstrap callback.
This is a convenience method for simple servers that don’t need initialization logic before starting.
§Example
use foxtive_ntex::http::server::ServerBuilder;
use foxtive::setup::FoxtiveSetup;
let foxtive = FoxtiveSetup::default();
ServerBuilder::production_mode("0.0.0.0", 8080, foxtive)
.run()
.await?;