HttpServer

Struct HttpServer 

Source
pub struct HttpServer<F, I, S, B>
where F: Fn() -> I + Send + Clone + 'static, I: IntoServiceFactory<S>, S: ServiceFactory<Config = AppConfig, Request = Request>, <S as ServiceFactory>::Error: Into<Error>, <S as ServiceFactory>::InitError: Debug, <S as ServiceFactory>::Response: Into<Response<B>>, B: MessageBody,
{ /* private fields */ }
Expand description

An HTTP Server.

Create new http server with application factory.

use actix_web::{web, App, HttpResponse, HttpServer};

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

Implementations§

Source§

impl<F, I, S, B> HttpServer<F, I, S, B>
where F: Fn() -> I + Send + Clone + 'static, I: IntoServiceFactory<S>, S: ServiceFactory<Config = AppConfig, Request = Request>, <S as ServiceFactory>::Error: Into<Error> + 'static, <S as ServiceFactory>::InitError: Debug, <S as ServiceFactory>::Response: Into<Response<B>> + 'static, <<S as ServiceFactory>::Service as Service>::Future: 'static, B: MessageBody + 'static,

Source

pub fn new(factory: F) -> HttpServer<F, I, S, B>

Create new http server with application factory

Source

pub fn on_connect<CB>(self, f: CB) -> HttpServer<F, I, S, B>
where CB: Fn(&(dyn Any + 'static), &mut Extensions) + Send + Sync + 'static,

Sets function that will be called once before each connection is handled. It will receive a &std::any::Any, which contains underlying connection type and an Extensions container so that request-local data can be passed to middleware and handlers.

For example:

  • actix_tls::openssl::SslStream<actix_web::rt::net::TcpStream> when using openssl.
  • actix_tls::rustls::TlsStream<actix_web::rt::net::TcpStream> when using rustls.
  • actix_web::rt::net::TcpStream when no encryption is used.

See on_connect example for additional details.

Source

pub fn workers(self, num: usize) -> HttpServer<F, I, S, B>

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) -> HttpServer<F, I, S, B>

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

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

Source

pub fn max_connections(self, num: usize) -> HttpServer<F, I, S, B>

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_connection_rate(self, num: usize) -> HttpServer<F, I, S, B>

Sets the maximum per-worker concurrent connection establish process.

All listeners will stop accepting connections when this limit is reached. It can be used to limit the global TLS CPU usage.

By default max connections is set to a 256.

Source

pub fn keep_alive<T>(self, val: T) -> HttpServer<F, I, S, B>
where T: Into<KeepAlive>,

Set server keep-alive setting.

By default keep alive is set to a 5 seconds.

Source

pub fn client_timeout(self, val: u64) -> HttpServer<F, I, S, B>

Set server client timeout in milliseconds for first request.

Defines a timeout for reading client request header. If a client does not transmit the entire set headers within this time, the request is terminated with the 408 (Request Time-out) error.

To disable timeout set value to 0.

By default client timeout is set to 5000 milliseconds.

Source

pub fn client_shutdown(self, val: u64) -> HttpServer<F, I, S, B>

Set server connection shutdown timeout in milliseconds.

Defines a timeout for shutdown connection. If a shutdown procedure does not complete within this time, the request is dropped.

To disable timeout set value to 0.

By default client timeout is set to 5000 milliseconds.

Source

pub fn server_hostname<T>(self, val: T) -> HttpServer<F, I, S, B>
where T: AsRef<str>,

Set server host name.

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

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

Source

pub fn system_exit(self) -> HttpServer<F, I, S, B>

Stop actix system.

Source

pub fn disable_signals(self) -> HttpServer<F, I, S, B>

Disable signal handling

Source

pub fn shutdown_timeout(self, sec: u64) -> HttpServer<F, I, S, B>

Timeout for graceful workers shutdown.

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

By default shutdown timeout sets to 30 seconds.

Source

pub fn addrs(&self) -> Vec<SocketAddr>

Get addresses of bound sockets.

Source

pub fn addrs_with_scheme(&self) -> Vec<(SocketAddr, &str)>

Get addresses of bound sockets and the scheme for it.

This is useful when the server is bound from different sources with some sockets listening on http and some listening on https and the user should be presented with an enumeration of which socket requires which protocol.

Source

pub fn listen(self, lst: TcpListener) -> Result<HttpServer<F, I, S, B>, Error>

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 bind<A>(self, addr: A) -> Result<HttpServer<F, I, S, B>, Error>
where A: ToSocketAddrs,

The socket address to bind

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

Source

pub fn listen_uds( self, lst: UnixListener, ) -> Result<HttpServer<F, I, S, B>, Error>

Start listening for unix domain (UDS) connections on existing listener.

Source

pub fn bind_uds<A>(self, addr: A) -> Result<HttpServer<F, I, S, B>, Error>
where A: AsRef<Path>,

Start listening for incoming unix domain connections.

Source§

impl<F, I, S, B> HttpServer<F, I, S, B>
where F: Fn() -> I + Send + Clone + 'static, I: IntoServiceFactory<S>, S: ServiceFactory<Config = AppConfig, Request = Request>, <S as ServiceFactory>::Error: Into<Error>, <S as ServiceFactory>::InitError: Debug, <S as ServiceFactory>::Response: Into<Response<B>>, <S as ServiceFactory>::Service: 'static, B: MessageBody,

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.

This methods panics if no socket address can be bound or an Actix system is not yet configured.

use std::io;
use actix_web::{web, App, HttpResponse, HttpServer};

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

Auto Trait Implementations§

§

impl<F, I, S, B> Freeze for HttpServer<F, I, S, B>

§

impl<F, I, S, B> !RefUnwindSafe for HttpServer<F, I, S, B>

§

impl<F, I, S, B> Send for HttpServer<F, I, S, B>
where <S as ServiceFactory>::Response: Sized, <S as ServiceFactory>::Error: Sized, S: Send, B: Send,

§

impl<F, I, S, B> !Sync for HttpServer<F, I, S, B>

§

impl<F, I, S, B> Unpin for HttpServer<F, I, S, B>
where <S as ServiceFactory>::Response: Sized, <S as ServiceFactory>::Error: Sized, F: Unpin, S: Unpin, B: Unpin,

§

impl<F, I, S, B> !UnwindSafe for HttpServer<F, I, S, B>

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

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoSql for T

Source§

fn into_sql<T>(self) -> Self::Expression
where Self: Sized + AsExpression<T>,

Convert self to an expression for Diesel’s query builder. Read more
Source§

fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
where &'a Self: AsExpression<T>,

Convert &self to an expression for Diesel’s query builder. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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 = 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.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,