pub struct Server { /* private fields */ }
Expand description
An HTTP server.
It currently provides two threading approaches:
- If the
rayon
feature is enabled a thread pool is used. The number of threads can be set with theServer::set_num_threads
feature. By default 4 times the number of available logical cores is used. - If the
rayon
feature is not enabled, a new thread is started on each connection and kept while the client connection is not closed. Use it at our own risks!
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()
}
});
// Raise a timeout error if the client does not respond after 10s.
server.set_global_timeout(Duration::from_secs(10));
// Listen to localhost:8080
server.listen(("localhost", 8080))?;
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 set_server_name(
&mut self,
server: impl Into<String>
) -> Result<(), InvalidHeader>
pub fn set_server_name( &mut self, server: impl Into<String> ) -> Result<(), InvalidHeader>
Sets the default value for the Server
header.
sourcepub fn set_global_timeout(&mut self, timeout: Duration)
pub fn set_global_timeout(&mut self, timeout: Duration)
Sets the global timeout value (applies to both read and write).
sourcepub fn set_num_threads(&mut self, num_threads: usize)
pub fn set_num_threads(&mut self, num_threads: usize)
Sets that the server should use a thread pool with this number of threads.
sourcepub fn listen(&self, address: impl ToSocketAddrs) -> Result<()>
pub fn listen(&self, address: impl ToSocketAddrs) -> Result<()>
Runs the server by listening to address
.