pub struct Server { /* private fields */ }
server
only.Expand description
An HTTP server.
It uses a very simple threading mechanism: a new thread is started on each connection and closed when the client connection is closed.
To avoid crashes it is possible to set an upper bound to the number of concurrent connections using the Server::with_max_concurrent_connections
function.
use std::net::{Ipv4Addr, Ipv6Addr};
use oxhttp::Server;
use oxhttp::model::{Response, Status};
use std::time::Duration;
// Builds a new server that returns a 404 everywhere except for "/" where it returns the body 'home'
let mut server = Server::new(|request| {
if request.url().path() == "/" {
Response::builder(Status::OK).with_body("home")
} else {
Response::builder(Status::NOT_FOUND).build()
}
});
// We bind the server to localhost on both IPv4 and v6
server = server.bind((Ipv4Addr::LOCALHOST, 8080)).bind((Ipv6Addr::LOCALHOST, 8080));
// Raise a timeout error if the client does not respond after 10s.
server = server.with_global_timeout(Duration::from_secs(10));
// Limits the number of concurrent connections to 128.
server = server.with_max_concurrent_connections(128);
// We spawn the server and block on it
server.spawn()?.join()?;
Implementations§
source§impl Server
impl Server
sourcepub fn new(
on_request: impl Fn(&mut Request) -> Response + Send + Sync + 'static
) -> Self
pub fn new( on_request: impl Fn(&mut Request) -> Response + Send + Sync + 'static ) -> Self
Builds the server using the given on_request
method that builds a Response
from a given Request
.
sourcepub fn bind(self, addr: impl Into<SocketAddr>) -> Self
pub fn bind(self, addr: impl Into<SocketAddr>) -> Self
Ask the server to listen to a given socket when spawned.
sourcepub fn with_server_name(
self,
server: impl Into<String>
) -> Result<Self, InvalidHeader>
pub fn with_server_name( self, server: impl Into<String> ) -> Result<Self, InvalidHeader>
Sets the default value for the Server
header.
sourcepub fn with_global_timeout(self, timeout: Duration) -> Self
pub fn with_global_timeout(self, timeout: Duration) -> Self
Sets the global timeout value (applies to both read and write).
sourcepub fn with_max_concurrent_connections(self, max_num_thread: usize) -> Self
pub fn with_max_concurrent_connections(self, max_num_thread: usize) -> Self
Sets the number maximum number of threads this server can spawn.
sourcepub fn spawn(self) -> Result<ListeningServer>
pub fn spawn(self) -> Result<ListeningServer>
Spawns the server by listening to the given addresses.
Note that this is not blocking.
To wait for the server to terminate indefinitely, call join
on the result.