Skip to main content

HttpServer

Struct HttpServer 

Source
pub struct HttpServer<Cfg, F, I, Sf>
where Cfg: ServerAppConfig, Cfg::State: Clone, F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static, I: IntoServiceFactory<Sf, Cfg::State, Request>, Sf: ServiceFactory<Cfg::State, Request>, Sf::Res: Into<Response>, Sf::Error: ResponseError, Sf::InitError: IntoFailure,
{ /* private fields */ }
Expand description

An HTTP Server.

Create new http server with application factory.

use ntex::web::{self, App, HttpResponse, HttpServer};

#[ntex::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(
        async |_| App::new()
            .service(web::resource("/").to(async || { HttpResponse::Ok() })))
        .bind("127.0.0.1:59090", ntex::SharedCfg::default())?
        .run()
        .await
}

Implementations§

Source§

impl<F, I, Sf> HttpServer<NoConfig, F, I, Sf>
where F: AsyncFn(&()) -> I + Send + Clone + 'static, I: IntoServiceFactory<Sf, (), Request>, Sf: ServiceFactory<(), Request> + 'static, Sf::Res: Into<Response>, Sf::Error: ResponseError, Sf::InitError: IntoFailure,

Source

pub fn new(factory: F) -> Self

Create new http server with application factory

Source§

impl<Cfg, F, I, Sf> HttpServer<Cfg, F, I, Sf>
where Cfg: ServerAppConfig, Cfg::State: Clone, F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static, I: IntoServiceFactory<Sf, Cfg::State, Request>, Sf: ServiceFactory<Cfg::State, Request> + 'static, Sf::Res: Into<Response>, Sf::Error: ResponseError, Sf::InitError: IntoFailure,

Source

pub fn with_config(cfg: Cfg, factory: F) -> Self
where Cfg: ServerAppConfig,

Create new http server with application factory and state mapping

Source

pub fn workers(self, num: usize) -> Self

Set number of workers to start.

By default http server uses number of available logical cpu as threads count.

Source

pub fn backlog(self, backlog: i32) -> Self

Set the maximum number of pending connections.

This refers to the number of clients that can be waiting to be served. Exceeding this number results in the client getting an error when attempting to connect. It should only affect servers under significant load.

Generally set in the 64-2048 range. Default value is 1024.

This method should be called before bind() method call.

Source

pub fn max_connections(self, num: usize) -> Self

Sets the maximum per-worker number of concurrent connections.

All socket listeners will stop accepting connections when this limit is reached for each worker.

By default max connections is set to a 25k.

Source

pub fn max_tls_handshakes(self, num: usize) -> Self

Sets the maximum per-worker number of concurrent TLS handshakes.

This limit applies only to TLS acceptors (OpenSSL and rustls). When it is reached, TLS acceptors stop accepting new handshakes until one completes. Plain TCP listeners are not affected. It can be used to limit the CPU usage of TLS handshakes.

By default the limit is 256.

Source

pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self

Set server host name.

Host name is used by application router as a hostname for url generation. Check ConnectionInfo::host() documentation for more information.

By default host name is set to a “localhost:8080” value.

Source

pub fn stop_runtime(self) -> Self

Stop ntex runtime when server get dropped.

By default “stop runtime” is disabled.

Source

pub fn stop_on_panic(self) -> Self

Stops the server when one of the workers panics.

By default, “stop on panic” is disabled.

Source

pub fn disable_signals(self) -> Self

Disable signal handling.

By default, signal handling is enabled.

Source

pub fn graceful_shutdown_timeout(self, sec: Seconds) -> Self

Timeout for graceful worker shutdown.

After receiving a stop signal, workers have this much time to finish serving requests. Workers that are still alive after the timeout are forcefully dropped.

This bounds the worker as a whole, not an individual connection. Each connection is bound separately by IoConfig::set_shutdown_timeout, so this value should leave room for the connections a worker is still draining to shut down themselves.

By default, the timeout is set to 30 seconds.

Source

pub fn enable_affinity(self) -> Self

Enable cpu affinity.

By default, affinity is disabled.

Source

pub fn graceful_shutdown(self) -> Self

Graceful shutdown.

When enabled, SIGQUIT, SIGSEGV, SIGABRT, and application panics stop the server gracefully. SIGTERM always stops the server gracefully, and SIGINT always stops it immediately.

By default, these events stop the server immediately.

Source

pub fn listen(self, lst: TcpListener, cfg: impl Into<SharedCfg>) -> Result<Self>

Use listener for accepting incoming connection requests

HttpServer does not change any configuration for TcpListener, it needs to be configured before passing it to listen() method.

Source

pub fn listen_openssl( self, lst: TcpListener, cfg: impl Into<SharedCfg>, builder: SslAcceptorBuilder, ) -> Result<Self>

Use listener for accepting incoming tls connection requests.

This method sets alpn protocols to “h2” and “http/1.1”

Source

pub fn listen_rustls( self, lst: TcpListener, cfg: impl Into<SharedCfg>, config: RustlsServerConfig, ) -> Result<Self>

Use listener for accepting incoming tls connection requests.

This method sets alpn protocols to “h2” and “http/1.1”

Source

pub fn bind<A: ToSocketAddrs>( self, addr: A, cfg: impl Into<SharedCfg>, ) -> Result<Self>

The socket address to bind.

To bind multiple addresses this method can be called multiple times.

Source

pub fn bind_openssl<A>( self, addr: A, builder: SslAcceptorBuilder, cfg: impl Into<SharedCfg>, ) -> Result<Self>
where A: ToSocketAddrs,

Start listening for incoming tls connections.

This method sets alpn protocols to “h2” and “http/1.1”

Source

pub fn bind_rustls<A: ToSocketAddrs>( self, addr: A, config: &RustlsServerConfig, cfg: impl Into<SharedCfg>, ) -> Result<Self>

Start listening for incoming tls connections.

This method sets alpn protocols to “h2” and “http/1.1”

Source

pub fn listen_uds( self, lst: UnixListener, cfg: impl Into<SharedCfg>, ) -> Result<Self>

Start listening for unix domain connections on existing listener.

This method is available only on Unix.

Source

pub fn bind_uds<A>(self, addr: A, cfg: impl Into<SharedCfg>) -> Result<Self>
where A: AsRef<Path>,

Start listening for incoming unix domain connections.

This method is available only on Unix.

Source§

impl<Cfg, F, I, Sf> HttpServer<Cfg, F, I, Sf>
where Cfg: ServerAppConfig, Cfg::State: Clone, F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static, I: IntoServiceFactory<Sf, Cfg::State, Request>, Sf: ServiceFactory<Cfg::State, Request> + 'static, Sf::Res: Into<Response>, Sf::Error: ResponseError, Sf::InitError: IntoFailure,

Source

pub fn run(self) -> Server

Start listening for incoming connections.

This method starts number of http workers in separate threads. For each address this method starts separate thread which does accept() in a loop.

§Panics

Panics if no listener was registered before calling this method.

use ntex::web::{self, App, HttpResponse, HttpServer};

#[ntex::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(
        async |_| App::new().service(web::resource("/").to(async || { HttpResponse::Ok() }))
    )
        .bind("127.0.0.1:0", ntex::SharedCfg::default())?
        .run()
        .await
}

Trait Implementations§

Source§

impl<Cfg, F, I, Sf> Debug for HttpServer<Cfg, F, I, Sf>
where Cfg: ServerAppConfig, Cfg::State: Clone, F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static, I: IntoServiceFactory<Sf, Cfg::State, Request>, Sf: ServiceFactory<Cfg::State, Request>, Sf::Res: Into<Response>, Sf::Error: ResponseError, Sf::InitError: IntoFailure,

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<Cfg, F, I, Sf> !RefUnwindSafe for HttpServer<Cfg, F, I, Sf>

§

impl<Cfg, F, I, Sf> !Sync for HttpServer<Cfg, F, I, Sf>

§

impl<Cfg, F, I, Sf> !UnwindSafe for HttpServer<Cfg, F, I, Sf>

§

impl<Cfg, F, I, Sf> Freeze for HttpServer<Cfg, F, I, Sf>

§

impl<Cfg, F, I, Sf> Send for HttpServer<Cfg, F, I, Sf>

§

impl<Cfg, F, I, Sf> Unpin for HttpServer<Cfg, F, I, Sf>

§

impl<Cfg, F, I, Sf> UnsafeUnpin for HttpServer<Cfg, F, I, Sf>

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