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.

§Panics

Panics if num is zero.

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 acceptors(self, num: usize) -> Self

Sets the number of accept threads.

Each accept thread has its own SO_REUSEPORT copy of every TCP listener, and the kernel spreads incoming connections between them. This raises the connection rate the server can accept. Unix domain listeners are served by a single accept thread.

Multiple accept threads are supported on Linux and Android. On other platforms, a single thread is used.

By default, the server uses a single accept thread. One thread is usually enough, add more only if the accept thread is saturated.

Source

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

Sets the maximum per-worker number of concurrent connections.

All socket listeners of this server stop accepting connections when every worker reaches this limit. The limit applies only to this server.

By default max connections is set to a 25k.

Source

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

Sets the per-worker soft limit on concurrent TLS handshakes.

This limit applies only to TLS acceptors (OpenSSL and rustls), which apply readiness backpressure when it is reached. Independent listener or service pipelines with cached readiness can still start handshakes and exceed the limit; it is not a strict admission limit. Plain TCP listeners are not affected.

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

👎Deprecated since 4.4.0:

affinity is enabled by default, use affinity() to change it

Does nothing, affinity is enabled by default.

Source

pub fn affinity(self, affinity: Affinity) -> Self

Sets the CPU affinity of worker threads.

Workers are spread over physical cores first, see Affinity.

By default, Affinity::Soft is used on Windows and Affinity::Core on other platforms.

Source

pub fn load_balancing(self, balancing: LoadBalancing) -> Self

Sets how new connections are distributed between workers.

By default, LoadBalancing::IncomingCpu sends new connections to idle workers, which helps when connections are long-lived or their load is uneven, and prefers the worker on the CPU that receives a connection’s network packets. LoadBalancing::RoundRobin sends them to the workers in turn. LoadBalancing::Reuseport lets each worker accept TCP connections on its own SO_REUSEPORT socket on Linux.

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. SIGSEGV and SIGABRT require runtime fatal signal handling, application panics require runtime panic handling.

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
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V