Skip to main content

RequestBuilder

Struct RequestBuilder 

Source
pub struct RequestBuilder<Target = Request>
where Target: From<Request>,
{ /* private fields */ }
Expand description

§Request Builder

Allows for construction and modification of request instances as it’s primary function; however, it can build directly to anything that can be built from a request.

let req: Request = RequestBuilder::default()
    .address_scheme(Scheme::Https)
    .address_host(Host::parse("example.com").unwrap())
    .address_port(8080)
    .header("Content-Type", "application/json")
    .query_param("key", "foo")
    .method(Method::Post)
    .path("/api/v1/resource")
    .body_text("my-resource")
    .build();

assert_eq!(req.address.port, Some(8080));
assert_eq!(req.address.host.to_string(), "example.com");
assert_eq!(req.address.scheme, Scheme::Https);
assert_eq!(req.method, Method::Post);
assert_eq!(req.path.as_str(), "/api/v1/resource");
assert_eq!(req.query.first("key"), Some("foo"));
assert_eq!(req.headers.first("content-type"), Some("application/json"));
assert_eq!(req.body.text(), Some("my-resource"));

Implementations§

Source§

impl<Target> RequestBuilder<Target>
where Target: From<Request>,

Source

pub fn address(self, address: Address) -> Self

sets the address for the request

due to the failable nature of the address host this allows for setting the whole address at once from an outside failable parse of it.

let example_address = Address::parse("https://example.com:8080")?;
let req = Request::builder()
    .address(example_address)
    .get("/index.html")
    .build();

assert_eq!(req.address.host.to_string(), "example.com");
assert_eq!(req.address.scheme, Scheme::Https);
assert_eq!(req.address.port, Some(8080));
assert_eq!(req.build_url().as_str(), "https://example.com:8080/index.html");

Source

pub fn address_port(self, port: u16) -> Self

set server address port number

Will automatically pick a port if not provided based on the scheme of the request at run-time and will report as none.

let http_default = Request::builder()
    .address_scheme(Scheme::Http)
    .build();

assert!(http_default.address.port.is_none());
assert_eq!(http_default.build_url().as_str(), "http://localhost/");

let https_default = Request::builder()
    .address_scheme(Scheme::Https)
    .build();

assert!(https_default.address.port.is_none());
assert_eq!(https_default.build_url().as_str(), "https://localhost/");

let http_custom = Request::builder()
    .address_scheme(Scheme::Http)
    .address_port(3001)
    .build();

assert_eq!(http_custom.address.port, Some(3001));
assert_eq!(http_custom.build_url().as_str(), "http://localhost:3001/");

let https_custom = Request::builder()
    .address_scheme(Scheme::Https)
    .address_port(3002)
    .build();

assert_eq!(https_custom.address.port, Some(3002));
assert_eq!(https_custom.build_url().as_str(), "https://localhost:3002/");

Source

pub fn address_host<H>(self, host: H) -> Self
where H: Into<Host>,

set server address host

This is an infailable process; unfortunately parsing a host name is not. Setting it once at boot in factories would allow preventing the need to parse it all of the time.

let host = Host::parse("example.com")?;
let req = Request::builder()
    .address_host(host)
    .build();

assert_eq!(req.build_url().as_str(), "http://example.com/");

Source

pub fn address_scheme<S>(self, scheme: S) -> Self
where S: Into<Scheme>,

set address scheme


Source

pub fn post<P>(self, path: P) -> Self
where P: Into<Path>,

POST path

let req = Request::builder()
    .header("Content-Type", "application/json")
    .post("/widgets")
    .body_text(r#"{"name":"foo"}"#)
    .build();

assert_eq!(req.method, Method::Post);
assert_eq!(req.headers.first("content-type"), Some("application/json"));
assert_eq!(req.path.as_str(), "/widgets");
assert_eq!(req.body.text(), Some(r#"{"name":"foo"}"#));

Source

pub fn get<P>(self, path: P) -> Self
where P: Into<Path>,

GET path

let request = Request::builder()
    .get("/api/v1/resource")
    .build();

assert_eq!(request.method, Method::Get);
assert_eq!(request.path.as_str(), "/api/v1/resource");
assert!(request.query.is_empty());

Source

pub fn delete<P>(self, path: P) -> Self
where P: Into<Path>,

DELETE path

let req = Request::builder()
    .header("Authorization", "Bearer some-token")
    .delete("/foo/123")
    .build();

assert_eq!(req.method, Method::Delete);
assert_eq!(req.headers.first("authorization"), Some("Bearer some-token"));
assert_eq!(req.path.as_str(), "/foo/123");
assert!(req.body.is_empty());

Source

pub fn put<P>(self, path: P) -> Self
where P: Into<Path>,

PUT path

let req = Request::builder()
    .header("Content-Type", "application/json")
    .put("/foo")
    .body_text("fiz-buz")
    .build();

assert_eq!(req.method, Method::Put);
assert_eq!(req.headers.first("content-type"), Some("application/json"));
assert_eq!(req.path.as_str(), "/foo");
assert_eq!(req.body.text(), Some("fiz-buz"));

Source

pub fn patch<P>(self, path: P) -> Self
where P: Into<Path>,

PATCH path

let req = Request::builder()
    .header("Authorization", "ApiKey $rofl$")
    .patch("/my/email")
    .body_text("domain=example.com")
    .build();

assert_eq!(req.method, Method::Patch);
assert_eq!(req.headers.first("authorization"), Some("ApiKey $rofl$"));
assert_eq!(req.path.as_str(), "/my/email");
assert_eq!(req.body.text(), Some("domain=example.com"));

Source

pub fn method(self, method: Method) -> Self

set the request method

let req = Request::builder()
    .method(Method::Options)
    .path("/api/*")
    .build();

assert_eq!(req.method, Method::Options);
assert_eq!(req.path.as_str(), "/api/*");

Source

pub fn path<P>(self, path: P) -> Self
where P: Into<Path>,

set the request path

let req = Request::builder().path("/foo").build();

assert_eq!(req.path.as_str(), "/foo");

Source

pub fn query_param<K, V>(self, key: K, value: V) -> Self
where K: Into<String>, V: Into<String>,

add a query parameter key/value pair


let req = Request::builder()
    .path("/api")
    .query_param("key", "value")
    .query_param("another", "value2")
    .build();

assert_eq!(req.query.first("key"), Some("value"));
assert_eq!(req.query.first("another"), Some("value2"));
assert_eq!(
    req.build_url().as_str(),
    "http://localhost/api?key=value&another=value2"
);

Source

pub fn multiple_query_params<I, Q>(self, params: I) -> Self
where Q: Into<QueryParameter>, I: IntoIterator<Item = Q>,

add multiple query parameters

let req = Request::builder()
    .path("/search")
    .multiple_query_params([
        ("q", "rust"),
        ("page", "1"),
    ])
    .build();

assert_eq!(req.query.first("q"), Some("rust"));
assert_eq!(req.query.first("page"), Some("1"));
assert_eq!(
    req.build_url().as_str(),
    "http://localhost/search?q=rust&page=1"
);

Source

pub fn with_query_string(self, query: QueryString) -> Self

sets the entire query string for the request

let query = QueryString::from_iter([
    ("foo", "bar"),
    ("bing", "bong"),
]);

let req = Request::builder()
    .with_query_string(query)
    .build();

assert_eq!(req.query.first("foo"), Some("bar"));
assert_eq!(req.query.first("bing"), Some("bong"));

Source

pub fn header(self, key: &str, value: &str) -> Self

add a header key/value pair

let req = Request::builder()
    .header("Content-Type", "application/json")
    .header("Authorization", "Bearer my-token")
    .build();

assert_eq!(req.headers.first("content-type"), Some("application/json"));
assert_eq!(req.headers.first("authorization"), Some("Bearer my-token"));

Source

pub fn multiple_headers<I, H>(self, header_lines: I) -> Self
where H: Into<HeaderLine>, I: IntoIterator<Item = H>,

add multiple header key/value pairs

let req = Request::builder()
    .multiple_headers([
        ("Authorization", "Bearer token"),
        ("Content-Type", "application/json"),
    ])
    .build();

assert_eq!(req.headers.first("authorization"), Some("Bearer token"));
assert_eq!(req.headers.first("content-type"), Some("application/json"));

Source

pub fn with_headers(self, headers: Headers) -> Self

sets the entire headers collection for the request

let headers = Headers::from_iter([
    ("Authorization", "Bearer token"),
    ("Content-Type", "application/json"),
]);

let req = Request::builder()
    .with_headers(headers)
    .build();

assert_eq!(req.headers.first("authorization"), Some("Bearer token"));
assert_eq!(req.headers.first("content-type"), Some("application/json"));

Source

pub fn body<B>(self, body: B) -> Self
where B: Into<RequestBody>,

Sets a body for the request.

let req = Request::builder()
    .post("/api/v1/resource")
    .body(RequestBody::Binary(vec![1, 2, 3, 4]))
    .build();

assert_eq!(req.body.data(), &[1, 2, 3, 4]);

Source

pub fn body_text<B>(self, body: B) -> Self
where B: Into<String>,

Prepares a text body for the request.

let req = Request::builder()
    .post("/api/v1/resource")
    .body_text(r#"{"name":"foo"}"#)
    .build();

assert_eq!(req.body.text(), Some(r#"{"name":"foo"}"#));

Source

pub fn body_binary<B>(self, body: B) -> Self
where B: Into<Vec<u8>>,

Prepares a binary body for the request.

let req = Request::builder()
    .post("/api/v1/resource")
    .body_binary([1, 2, 3, 4])
    .build();

assert_eq!(req.body.data(), &[1, 2, 3, 4]);

Source

pub fn body_none(self) -> Self

Prepares an empty body for the request.

This is the default state of a request body and you only need to call this if you want to change the body back to empty.

let req = Request::builder()
    .get("/api/v1/resource")
    .body_none()
    .build();

assert!(req.body.is_empty());
assert_eq!(req.body, RequestBody::None);
assert_eq!(req.body.text(), None);
assert_eq!(req.body.data(), &[]);
assert_eq!(req.body.len(), 0);

Source

pub fn build(self) -> Target

builds the request or target type

The target type must implement From<Request> and is normally just Request itself. It is also used by factories to build directly


Trait Implementations§

Source§

impl<Target> Clone for RequestBuilder<Target>
where Target: From<Request> + Clone,

Source§

fn clone(&self) -> RequestBuilder<Target>

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<Target> Debug for RequestBuilder<Target>
where Target: From<Request> + Debug,

Source§

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

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

impl<Target> Default for RequestBuilder<Target>
where Target: From<Request> + Default,

Source§

fn default() -> RequestBuilder<Target>

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

impl<Target> PartialEq for RequestBuilder<Target>
where Target: From<Request> + PartialEq,

Source§

fn eq(&self, other: &RequestBuilder<Target>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Target> StructuralPartialEq for RequestBuilder<Target>
where Target: From<Request>,

Auto Trait Implementations§

§

impl<Target> Freeze for RequestBuilder<Target>

§

impl<Target> RefUnwindSafe for RequestBuilder<Target>
where Target: RefUnwindSafe,

§

impl<Target> Send for RequestBuilder<Target>
where Target: Send,

§

impl<Target> Sync for RequestBuilder<Target>
where Target: Sync,

§

impl<Target> Unpin for RequestBuilder<Target>
where Target: Unpin,

§

impl<Target> UnsafeUnpin for RequestBuilder<Target>

§

impl<Target> UnwindSafe for RequestBuilder<Target>
where Target: UnwindSafe,

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, 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> ErasedDestructor for T
where T: 'static,