Struct crux_http::RequestBuilder

source ·
pub struct RequestBuilder<Event, ExpectBody = Vec<u8>> { /* private fields */ }
Expand description

Request Builder

Provides an ergonomic way to chain the creation of a request. This is generally accessed as the return value from Http::{method}().

§Examples

use crux_http::http::{mime::HTML};
caps.http
    .post("https://httpbin.org/post")
    .body("<html>hi</html>")
    .header("custom-header", "value")
    .content_type(HTML)
    .send(Event::ReceiveResponse)

Implementations§

source§

impl<Event, ExpectBody> RequestBuilder<Event, ExpectBody>
where Event: 'static, ExpectBody: 'static,

source

pub fn header( self, key: impl Into<HeaderName>, value: impl ToHeaderValues ) -> Self

Sets a header on the request.

§Examples
caps.http
    .get("https://httpbin.org/get")
    .body("<html>hi</html>")
    .header("header-name", "header-value")
    .send(Event::ReceiveResponse)
source

pub fn content_type(self, content_type: impl Into<Mime>) -> Self

Sets the Content-Type header on the request.

§Examples
caps.http
    .get("https://httpbin.org/get")
    .content_type(mime::HTML)
    .send(Event::ReceiveResponse)
source

pub fn body(self, body: impl Into<Body>) -> Self

Sets the body of the request from any type with implements Into<Body>, for example, any type with is AsyncRead.

§Mime

The encoding is set to application/octet-stream.

§Examples
use serde_json::json;
use crux_http::http::mime;
caps.http
    .post("https://httpbin.org/post")
    .body(json!({"any": "Into<Body>"}))
    .content_type(mime::HTML)
    .send(Event::ReceiveResponse)
source

pub fn body_json(self, json: &impl Serialize) -> Result<Self>

Pass JSON as the request body.

§Mime

The encoding is set to application/json.

§Errors

This method will return an error if the provided data could not be serialized to JSON.

§Examples
#[derive(Deserialize, Serialize)]
struct Ip {
    ip: String
}

let data = &Ip { ip: "129.0.0.1".into() };
caps.http
    .post("https://httpbin.org/post")
    .body_json(data)
    .expect("could not serialize body")
    .send(Event::ReceiveResponse)
source

pub fn body_string(self, string: String) -> Self

Pass a string as the request body.

§Mime

The encoding is set to text/plain; charset=utf-8.

§Examples
caps.http
    .post("https://httpbin.org/post")
    .body_string("hello_world".to_string())
    .send(Event::ReceiveResponse)
source

pub fn body_bytes(self, bytes: impl AsRef<[u8]>) -> Self

Pass bytes as the request body.

§Mime

The encoding is set to application/octet-stream.

§Examples
caps.http
    .post("https://httpbin.org/post")
    .body_bytes(b"hello_world".to_owned())
    .send(Event::ReceiveResponse)
source

pub fn query(self, query: &impl Serialize) -> Result<Self, HttpError>

Set the URL querystring.

§Examples
#[derive(Serialize, Deserialize)]
struct Index {
    page: u32
}

let query = Index { page: 2 };
caps.http
    .post("https://httpbin.org/post")
    .query(&query)
    .expect("could not serialize query string")
    .send(Event::ReceiveResponse)
source

pub fn middleware(self, middleware: impl Middleware) -> Self

Push middleware onto a per-request middleware stack.

Important: Setting per-request middleware incurs extra allocations. Creating a Client with middleware is recommended.

Client middleware is run before per-request middleware.

See the middleware submodule for more information on middleware.

§Examples

caps.http
    .get("https://httpbin.org/redirect/2")
    .middleware(crux_http::middleware::Redirect::default())
    .send(Event::ReceiveResponse)
source

pub fn build(self) -> Request

Return the constructed Request.

source

pub fn expect_string(self) -> RequestBuilder<Event, String>

Decode a String from the response body prior to dispatching it to the apps update function.

This has no effect when used with the async API.

§Examples
enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<String>>) }

caps.http
    .post("https://httpbin.org/json")
    .expect_string()
    .send(Event::ReceiveResponse)
source

pub fn expect_json<T>(self) -> RequestBuilder<Event, T>
where T: DeserializeOwned + 'static,

Decode a T from a JSON response body prior to dispatching it to the apps update function.

This has no effect when used with the async API.

§Examples
#[derive(Deserialize)]
struct Response {
    slideshow: Slideshow
}

#[derive(Deserialize)]
struct Slideshow {
    author: String
}

enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Slideshow>>) }

caps.http
    .post("https://httpbin.org/json")
    .expect_json::<Slideshow>()
    .send(Event::ReceiveResponse)
source

pub fn send<F>(self, make_event: F)
where F: FnOnce(Result<Response<ExpectBody>>) -> Event + Send + 'static,

Sends the constructed Request and returns its result as an update Event

When finished, the response will wrapped in an event using make_event and dispatched to the app’s `update function.

source

pub fn send_async(self) -> BoxFuture<'static, Result<ResponseAsync>>

Sends the constructed Request and returns a future that resolves to ResponseAsync. but does not consume it or convert the body to an expected format.

Note that this is equivalent to calling .into_future() on the RequestBuilder, which will happen implicitly when calling .await on the builder, which does implement IntoFuture. Calling .await on the builder is recommended.

Not all code working with futures (such as the join macro) works with IntoFuture (yet?), so this method is provided as a more discoverable .into_future alias, and may be deprecated later.

Trait Implementations§

source§

impl<Ev> Debug for RequestBuilder<Ev>

source§

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

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

impl<T, Eb> IntoFuture for RequestBuilder<T, Eb>

source§

fn into_future(self) -> Self::IntoFuture

Sends the constructed Request and returns a future that resolves to the response

§

type Output = Result<ResponseAsync, HttpError>

The output that the future will produce on completion.
§

type IntoFuture = Pin<Box<dyn Future<Output = Result<ResponseAsync, HttpError>> + Send>>

Which kind of future are we turning this into?

Auto Trait Implementations§

§

impl<Event, ExpectBody> Freeze for RequestBuilder<Event, ExpectBody>

§

impl<Event, ExpectBody = Vec<u8>> !RefUnwindSafe for RequestBuilder<Event, ExpectBody>

§

impl<Event, ExpectBody> Send for RequestBuilder<Event, ExpectBody>

§

impl<Event, ExpectBody = Vec<u8>> !Sync for RequestBuilder<Event, ExpectBody>

§

impl<Event, ExpectBody> Unpin for RequestBuilder<Event, ExpectBody>

§

impl<Event, ExpectBody = Vec<u8>> !UnwindSafe for RequestBuilder<Event, ExpectBody>

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

§

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

§

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