Skip to main content

Server

Struct Server 

Source
pub struct Server { /* private fields */ }
Available on crate feature std only.
Expand description

A blocking HTTP/1.1 server: one thread per connection, bounded.

§Examples

use http_net::{blocking::{self, Server}, Response};

let server = Server::bind("127.0.0.1:0")?;
let addr = server.local_addr();
let stop = server.shutdown_handle();
let thread = std::thread::spawn(move || {
    server.serve(|req, _body| Response::text(200, &format!("you asked for {}", req.path())))
});

let resp = blocking::get(&format!("http://{addr}/hello"))?;
assert_eq!(resp.status(), 200);
assert_eq!(resp.text(), Some("you asked for /hello"));

stop.shutdown();
thread.join().unwrap()?;

Implementations§

Source§

impl Server

Source

pub fn bind(addr: impl ToSocketAddrs) -> Result<Self>

Binds a listening socket. Use 127.0.0.1:0 for an ephemeral localhost port and read it back with local_addr.

§Errors

The bind error from the operating system.

§Examples
let server = http_net::blocking::Server::bind("127.0.0.1:0")?;
assert!(server.local_addr().ip().is_loopback());
Source

pub fn with_config(self, config: ServerConfig) -> Self

Replaces the configuration.

§Examples
use http_net::blocking::{Server, ServerConfig};
let s = Server::bind("127.0.0.1:0")?.with_config(ServerConfig::new().with_max_connections(4));
Source

pub fn on_upgrade(self, hook: impl Fn(Upgraded) + Send + Sync + 'static) -> Self

Sets what happens to a connection after the handler answers with 101 Switching Protocols (or a 2xx to CONNECT): hook receives the socket on the connection’s thread. Without a hook such connections are closed.

§Examples

See Upgraded.

Source

pub fn local_addr(&self) -> SocketAddr

The bound address (with the real port when bound to port 0).

§Examples
let server = http_net::blocking::Server::bind("127.0.0.1:0")?;
assert_ne!(server.local_addr().port(), 0);
Source

pub fn shutdown_handle(&self) -> ShutdownHandle

A handle that stops serve from another thread.

§Examples

See ShutdownHandle.

Source

pub fn serve<H>(self, handler: H) -> Result<()>
where H: Fn(&RequestHead<'_>, &[u8]) -> Response + Send + Sync + 'static,

Serves handler until ShutdownHandle::shutdown is called.

The handler gets each request’s head and its complete body (bounded by Limits::max_body) and returns the response. Requests that fail to parse are answered with Response::from_error and the connection is closed; the handler never sees them. A request with Expect: 100-continue gets 100 Continue before its body is read; one with any other expectation is answered 417 Expectation Failed without reading its body (RFC 9110 section 10.1.1), and the connection is closed. A handler that returns a streamed response (chunked or content_length, except to HEAD), or one that ServerConn::respond refuses, is replaced by a 500 with connection: close. Every response gets a date field (from now_date) unless the handler set one, except the 503 sent to a connection over the connection cap. The time limits and the request cap of ServerConfig apply to every connection.

§Errors

Only if accepting connections fails persistently; transient accept errors are retried. Before the error is returned, live connections finish their current exchange, as after a shutdown.

§Examples

See Server.

Trait Implementations§

Source§

impl Debug for Server

Source§

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

Formats the value using the given formatter. Read more

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.