Skip to main content

Server

Struct Server 

Source
pub struct Server { /* private fields */ }
Expand description

Serves static HTTP content with configurable runtime policies.

You use Server as the main entrypoint to bind an address, map requests to files under a document root, and apply response policies such as CORS, cache hints, and simple rate limiting.

For most production setups, prefer Server::builder so optional settings are explicit and readable.

§Examples

use http_handle::Server;

let server = Server::new("127.0.0.1:8080", ".");
assert_eq!(server.address(), "127.0.0.1:8080");

§Panics

This type does not panic on construction.

Implementations§

Source§

impl Server

Source

pub fn new(address: &str, document_root: &str) -> Self

Creates a server using the minimal required configuration.

Use this constructor when you want a quick default path. For advanced runtime policy, prefer Server::builder.

§Examples
use http_handle::Server;

let server = Server::new("127.0.0.1:8080", ".");
assert_eq!(server.address(), "127.0.0.1:8080");
§Panics

This function does not panic.

Source

pub fn builder() -> ServerBuilder

Returns a fluent builder for optional server policies.

§Examples
use http_handle::Server;

let server = Server::builder()
    .address("127.0.0.1:8080")
    .document_root(".")
    .build()
    .expect("builder should succeed");
assert_eq!(server.address(), "127.0.0.1:8080");
§Panics

This function does not panic.

Source

pub fn start(&self) -> Result<()>

Starts a blocking HTTP/1.1 listener loop.

On Linux, macOS, and Windows, this binds a TcpListener and accepts connections in a thread-per-connection model.

§Examples
use http_handle::Server;

let server = Server::new("127.0.0.1:8080", ".");
let _ = server.start();
§Errors

Returns Err if binding fails or the listener cannot be configured.

§Panics

This function does not intentionally panic.

Source

pub fn start_with_graceful_shutdown( &self, shutdown_timeout: Duration, ) -> Result<()>

Starts the server with OS-signal-aware graceful shutdown.

On macOS/Linux, this responds to SIGINT/SIGTERM via the installed signal handler. On Windows, Ctrl+C triggers equivalent shutdown behavior through the same handler API.

§Examples
use http_handle::Server;
use std::time::Duration;

let server = Server::new("127.0.0.1:8080", ".");
let _ = server.start_with_graceful_shutdown(Duration::from_secs(5));
§Errors

Returns Err when binding or socket configuration fails.

§Panics

This function does not intentionally panic.

Source

pub fn start_with_shutdown_signal( &self, shutdown: Arc<ShutdownSignal>, ) -> Result<()>

Starts the server with caller-managed shutdown coordination.

§Examples
use http_handle::{Server, ShutdownSignal};
use std::sync::Arc;
use std::time::Duration;

let server = Server::new("127.0.0.1:8080", ".");
let signal = Arc::new(ShutdownSignal::new(Duration::from_secs(2)));
let _ = server.start_with_shutdown_signal(signal);
§Errors

Returns Err when binding or listener configuration fails.

§Panics

This function does not intentionally panic.

Source

pub fn start_with_shutdown_signal_and_ready<F>( &self, shutdown: Arc<ShutdownSignal>, on_ready: F, ) -> Result<()>
where F: FnOnce(String),

Starts the server with a shutdown signal and reports the actual bound address.

This is useful when binding to port 0 in tests and callers need the kernel-assigned port before sending requests.

§Arguments
  • shutdown - The shutdown signal to coordinate graceful termination
  • on_ready - Callback invoked once with the actual bound ip:port
§Returns

A Result indicating success or an I/O error.

Source

pub fn start_with_thread_pool(&self, thread_pool_size: usize) -> Result<()>

Starts the server with thread pooling for better resource management under load.

This method uses a fixed-size thread pool to handle connections, preventing resource exhaustion under high load by limiting the number of concurrent threads.

§Arguments
  • thread_pool_size - The number of worker threads in the pool
§Returns

A Result indicating success or an I/O error.

Source

pub fn start_with_pooling( &self, thread_pool_size: usize, max_connections: usize, ) -> Result<()>

Starts the server with both thread pooling and connection pooling for optimal resource management.

This method provides the highest level of resource control by combining:

  • Fixed-size thread pool to limit concurrent worker threads
  • Connection pool to limit the number of simultaneously processed connections
  • Graceful degradation when limits are reached
§Arguments
  • thread_pool_size - The number of worker threads in the pool
  • max_connections - The maximum number of concurrent connections to process
§Returns

A Result indicating success or an I/O error.

Source

pub fn cors_enabled(&self) -> Option<bool>

Returns the CORS enabled setting

Source

pub fn cors_origins(&self) -> &Option<Vec<String>>

Returns the CORS origins setting

Source

pub fn custom_headers(&self) -> &Option<HashMap<String, String>>

Returns the custom headers setting

Source

pub fn request_timeout(&self) -> Option<Duration>

Returns the request timeout setting

Source

pub fn connection_timeout(&self) -> Option<Duration>

Returns the connection timeout setting

Source

pub fn address(&self) -> &str

Returns the server address

Source

pub fn document_root(&self) -> &PathBuf

Returns the document root path

Trait Implementations§

Source§

impl Clone for Server

Source§

fn clone(&self) -> Server

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Server

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Server

Source§

fn default() -> Server

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Server

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for Server

Source§

fn eq(&self, other: &Server) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Server

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Server

Source§

impl StructuralPartialEq for Server

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,