HttpServerBuilder

Struct HttpServerBuilder 

Source
pub struct HttpServerBuilder<T, L>
where T: ToSocketAddrs + Default + Clone, L: Layer<HandlerFn> + Clone + Send + 'static,
{ /* private fields */ }
Expand description

HttpServerBuilder is a builder for configuring and initializing an HttpServer. It allows for setting up the server address, adding services, and configuring shared state.

Implementations§

Source§

impl<T, L> HttpServerBuilder<T, L>
where T: ToSocketAddrs + Default + Debug + Clone, L: Layer<HandlerFn> + Clone + Send + 'static, L::Service: Service<(HttpRequest, HttpPayload), Response = HttpResponse, Error = Error> + Send + 'static, <L::Service as Service<(HttpRequest, HttpPayload)>>::Future: Send + 'static,

Source

pub fn app_state<S: Send + Sync + 'static>(self, state: S) -> Self

Adds shared application state to be accessible in request handlers.

State is stored in a HashMap and keyed based on the TypeId of the state object.

§Arguments
  • state: A state object of type S that implements Send + Sync + 'static.
§Returns

The builder instance with the shared state added.

§Examples
struct MyState {
    state: String
}

let builder = HttpServer::builder()
    .with_state(MyState { state: "Hello, world!".to_string() })
    .bind("127.0.0.1:8080");
Examples found in repository?
examples/basic.rs (line 195)
188async fn main() -> Result<(), HttpServerError> {
189    logger::init_tracing()?;
190    let state = State {
191        dir: "/Users/emil/projects/tosic-http/target/doc".to_string(),
192    };
193
194    let server = HttpServerBuilder::default()
195        .app_state(state)
196        .bind("0.0.0.0:4221")
197        //.service_method(Method::POST, "/", test_handler)
198        .route(post("/", test_handler).get(test_get))
199        //.service_method(Method::GET, "/bad", not_working)
200        .service(not_working)
201        .service(test_fn)
202        //.service(website)
203        .build()
204        .await?;
205
206    match server.serve().await {
207        Ok(_) => (),
208        Err(e) => panic!("Failed to serve: {}", e),
209    }
210
211    Ok(())
212}
Source

pub fn service_method<H, Args>( self, method: Method, path: &str, handler: H, ) -> Self
where H: Handler<Args> + Send + Sync + 'static, Args: FromRequest + Send + 'static, Args::Future: Future + Send + 'static, H::Future: Future + Send + 'static, H::Output: Responder<Body = BoxBody> + 'static, Error: From<Args::Error>,

Adds a service handler to the server.

§Arguments
  • method: The HTTP method for the service endpoint.
  • path: The path of the service endpoint.
  • handler: A handler implementing the Handler trait, defining a service endpoint.
§Returns

The builder instance with the handler added.

§Examples

async fn basic_handler() -> impl Responder<Body = BoxBody> {
    HttpResponse::new(200)
}

let builder = HttpServer::builder()
    .service_method(Method::GET, "/", basic_handler)
    .bind("127.0.0.1:8080");
Source

pub fn service<H, Args>(self, handler: H) -> Self
where H: HttpService<Args> + Handler<Args> + Send + Sync + 'static, Args: FromRequest + Send + 'static, Args::Future: Future + Send + 'static, H::Future: Future + Send + 'static, H::Output: Responder<Body = BoxBody> + 'static, Error: From<Args::Error>,

Adds a service handler to the server.

§Arguments
§Returns

The builder instance with the handler added.

§Examples

#[get("/")]
async fn basic_handler() -> impl Responder<Body = BoxBody> {
    HttpResponse::new(200)
}

let builder = HttpServer::builder()
    .service(basic_handler)
    .bind("127.0.0.1:8080");
Examples found in repository?
examples/device_id.rs (line 116)
111async fn main() -> Result<(), HttpServerError> {
112    logger::init_tracing()?;
113
114    let server = HttpServerBuilder::default()
115        .bind("0.0.0.0:4221")
116        .service(devices)
117        .build()
118        .await?;
119
120    match server.serve().await {
121        Ok(_) => (),
122        Err(e) => panic!("Failed to serve: {}", e),
123    }
124
125    Ok(())
126}
More examples
Hide additional examples
examples/basic.rs (line 200)
188async fn main() -> Result<(), HttpServerError> {
189    logger::init_tracing()?;
190    let state = State {
191        dir: "/Users/emil/projects/tosic-http/target/doc".to_string(),
192    };
193
194    let server = HttpServerBuilder::default()
195        .app_state(state)
196        .bind("0.0.0.0:4221")
197        //.service_method(Method::POST, "/", test_handler)
198        .route(post("/", test_handler).get(test_get))
199        //.service_method(Method::GET, "/bad", not_working)
200        .service(not_working)
201        .service(test_fn)
202        //.service(website)
203        .build()
204        .await?;
205
206    match server.serve().await {
207        Ok(_) => (),
208        Err(e) => panic!("Failed to serve: {}", e),
209    }
210
211    Ok(())
212}
Source

pub fn route(self, route_builder: RouteBuilder<'_>) -> Self

Adds a route to the server.

§Arguments
  • route_builder: A builder for defining the route.
§Returns

The builder instance with the route added.

Examples found in repository?
examples/basic.rs (line 198)
188async fn main() -> Result<(), HttpServerError> {
189    logger::init_tracing()?;
190    let state = State {
191        dir: "/Users/emil/projects/tosic-http/target/doc".to_string(),
192    };
193
194    let server = HttpServerBuilder::default()
195        .app_state(state)
196        .bind("0.0.0.0:4221")
197        //.service_method(Method::POST, "/", test_handler)
198        .route(post("/", test_handler).get(test_get))
199        //.service_method(Method::GET, "/bad", not_working)
200        .service(not_working)
201        .service(test_fn)
202        //.service(website)
203        .build()
204        .await?;
205
206    match server.serve().await {
207        Ok(_) => (),
208        Err(e) => panic!("Failed to serve: {}", e),
209    }
210
211    Ok(())
212}
Source

pub fn bind(self, addr: T) -> Self

Sets the address the server will bind to.

§Arguments
  • addr: The address for the server to bind, implementing ToSocketAddrs.
§Returns

Returns the builder instance with the binding address set.

§Examples
let builder = HttpServer::builder()
    .bind("127.0.0.1:8080");
Examples found in repository?
examples/device_id.rs (line 115)
111async fn main() -> Result<(), HttpServerError> {
112    logger::init_tracing()?;
113
114    let server = HttpServerBuilder::default()
115        .bind("0.0.0.0:4221")
116        .service(devices)
117        .build()
118        .await?;
119
120    match server.serve().await {
121        Ok(_) => (),
122        Err(e) => panic!("Failed to serve: {}", e),
123    }
124
125    Ok(())
126}
More examples
Hide additional examples
examples/basic.rs (line 196)
188async fn main() -> Result<(), HttpServerError> {
189    logger::init_tracing()?;
190    let state = State {
191        dir: "/Users/emil/projects/tosic-http/target/doc".to_string(),
192    };
193
194    let server = HttpServerBuilder::default()
195        .app_state(state)
196        .bind("0.0.0.0:4221")
197        //.service_method(Method::POST, "/", test_handler)
198        .route(post("/", test_handler).get(test_get))
199        //.service_method(Method::GET, "/bad", not_working)
200        .service(not_working)
201        .service(test_fn)
202        //.service(website)
203        .build()
204        .await?;
205
206    match server.serve().await {
207        Ok(_) => (),
208        Err(e) => panic!("Failed to serve: {}", e),
209    }
210
211    Ok(())
212}
Source

pub async fn build(self) -> Result<HttpServer<L>>

Builds and initializes the HttpServer with the current configuration.

§Errors

Returns io::Error if there was an error initializing the server.

§Examples
let server = HttpServer::builder()
    .bind("127.0.0.1:8080")
    .build()
    .await
    .unwrap();
Examples found in repository?
examples/device_id.rs (line 117)
111async fn main() -> Result<(), HttpServerError> {
112    logger::init_tracing()?;
113
114    let server = HttpServerBuilder::default()
115        .bind("0.0.0.0:4221")
116        .service(devices)
117        .build()
118        .await?;
119
120    match server.serve().await {
121        Ok(_) => (),
122        Err(e) => panic!("Failed to serve: {}", e),
123    }
124
125    Ok(())
126}
More examples
Hide additional examples
examples/basic.rs (line 203)
188async fn main() -> Result<(), HttpServerError> {
189    logger::init_tracing()?;
190    let state = State {
191        dir: "/Users/emil/projects/tosic-http/target/doc".to_string(),
192    };
193
194    let server = HttpServerBuilder::default()
195        .app_state(state)
196        .bind("0.0.0.0:4221")
197        //.service_method(Method::POST, "/", test_handler)
198        .route(post("/", test_handler).get(test_get))
199        //.service_method(Method::GET, "/bad", not_working)
200        .service(not_working)
201        .service(test_fn)
202        //.service(website)
203        .build()
204        .await?;
205
206    match server.serve().await {
207        Ok(_) => (),
208        Err(e) => panic!("Failed to serve: {}", e),
209    }
210
211    Ok(())
212}
Source

pub fn wrap<S>(self, layer: S) -> HttpServerBuilder<T, Stack<S, L>>
where S: Layer<HandlerFn> + Clone + Send + 'static, L: Layer<S::Service> + Clone + Send + 'static,

Wraps a layer in the stack.

A layer is a middleware that can modify the request and response.

Trait Implementations§

Source§

impl<T, L> Clone for HttpServerBuilder<T, L>
where T: ToSocketAddrs + Default + Clone + Clone, L: Layer<HandlerFn> + Clone + Send + 'static + Clone,

Source§

fn clone(&self) -> HttpServerBuilder<T, L>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T, L> Debug for HttpServerBuilder<T, L>
where T: ToSocketAddrs + Default + Clone + Debug, L: Layer<HandlerFn> + Clone + Send + 'static + Debug,

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<T: ToSocketAddrs + Default + Debug + Clone> Default for HttpServerBuilder<T, Identity>

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl<T, L> Freeze for HttpServerBuilder<T, L>
where T: Freeze, L: Freeze,

§

impl<T, L> !RefUnwindSafe for HttpServerBuilder<T, L>

§

impl<T, L> Send for HttpServerBuilder<T, L>
where T: Send,

§

impl<T, L> Sync for HttpServerBuilder<T, L>
where T: Sync, L: Sync,

§

impl<T, L> Unpin for HttpServerBuilder<T, L>
where T: Unpin, L: Unpin,

§

impl<T, L> !UnwindSafe for HttpServerBuilder<T, L>

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