Skip to main content

Server

Struct Server 

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

An HTTP/1.1 server. Configure it, then call serve from each worker of a giong runtime.

use std::time::Duration;
use giong::net::TcpListener;
use giong_http::{Request, Response, Server};

async fn hello(req: Request) -> Response {
    match (req.method(), req.path()) {
        ("GET", "/") => Response::text("hello"),
        _ => Response::new(404),
    }
}

fn main() -> std::io::Result<()> {
    giong::Builder::new()
        .shutdown_on_signals(true)
        .shutdown_grace(Duration::from_secs(10))
        .build()?
        .run(|_worker| async {
            let listener = TcpListener::bind("0.0.0.0:8080").expect("bind");
            Server::new().serve(listener, hello).await;
        })
}

Implementations§

Source§

impl Server

Source

pub fn new() -> Self

A server with the default limits and timeouts.

Source

pub fn idle_timeout(self, timeout: Duration) -> Self

How long a keep-alive connection may sit between requests before it is closed (default: 60 s).

Source

pub fn request_timeout(self, timeout: Duration) -> Self

How long a client may take to send one complete request, counted from the moment the server first has to wait for more of it (default: 30 s). Slower clients get 408 Request Timeout.

Source

pub fn write_timeout(self, timeout: Duration) -> Self

How long a client may take to accept a batch of responses before the connection is dropped (default: 30 s).

Source

pub fn max_head_size(self, bytes: usize) -> Self

Largest accepted request head, in bytes (default: 64 KiB). Larger heads get 431 Request Header Fields Too Large.

Source

pub fn max_body_size(self, bytes: usize) -> Self

Largest accepted request body, in bytes (default: 1 MiB). Larger bodies get 413 Content Too Large.

Source

pub fn shutdown_linger(self, linger: Duration) -> Self

After a shutdown is requested, how long the server keeps picking up connections and requests that were already on their way (default: 100 ms). Requests in progress are not affected by this: they get the runtime’s shutdown_grace.

Source

pub async fn serve<H, Fut>(&self, listener: TcpListener, handler: H)
where H: Fn(Request) -> Fut + 'static, Fut: Future<Output = Response> + 'static,

Accepts connections on listener and answers their requests with handler until the runtime is asked to shut down.

Each connection runs as its own task on the current worker. When a shutdown is requested, the listener stops accepting, idle connections are closed, and requests being handled are finished and answered with Connection: close, within the grace period configured on the runtime.

A handler that panics takes down its connection only.

Source

pub async fn serve_unix<H, Fut>(&self, listener: UnixListener, handler: H)
where H: Fn(Request) -> Fut + 'static, Fut: Future<Output = Response> + 'static,

Like serve, on a Unix domain socket: the usual way to sit behind a reverse proxy on the same machine.

let listener = UnixListener::bind("/run/app.sock")?;
Server::new().serve_unix(listener, handler).await;
Source

pub async fn serve_tls<H, Fut>( &self, listener: TcpListener, acceptor: TlsAcceptor, handler: H, )
where H: Fn(Request) -> Fut + 'static, Fut: Future<Output = Response> + 'static,

Like serve, over TLS: every accepted connection first completes a TLS handshake with acceptor.

let acceptor = giong_tls::TlsAcceptor::from_pem(
    &std::fs::read("cert.pem")?,
    &std::fs::read("key.pem")?,
)?;
let listener = TcpListener::bind("0.0.0.0:8443")?;
Server::new().serve_tls(listener, acceptor, handler).await;
Source

pub async fn serve_connection<T, H, Fut>(&self, stream: T, handler: Rc<H>)
where T: Transport, H: Fn(Request) -> Fut + 'static, Fut: Future<Output = Response> + 'static,

Serves a single, already established connection until it is closed. For servers that run their own accept loop or their own transport.

Trait Implementations§

Source§

impl Clone for Server

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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() -> Self

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

Auto Trait Implementations§

§

impl Forget for Server

§

impl Freeze for Server

§

impl Move for Server

§

impl RefUnwindSafe for Server

§

impl Send for Server

§

impl Sync for Server

§

impl Unpin for Server

§

impl UnsafeUnpin for Server

§

impl UnwindSafe for Server

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
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> 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 = !

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.