Skip to main content

Request

Struct Request 

Source
pub struct Request { /* private fields */ }
Expand description

An outgoing HTTP request, built step by step and sent with send.

§Examples

use ocre::http::Request;
use serde_json::json;

let request = Request::post("https://api.example.com/v1/jobs")
    .bearer("rk_123")
    .header("Idempotency-Key", "job-42")
    .json(&json!({"input": {"video": "a.mp4"}}));
assert_eq!(request.method(), "POST");
assert_eq!(request.headers(), [
    ("authorization".to_owned(), "Bearer rk_123".to_owned()),
    ("idempotency-key".to_owned(), "job-42".to_owned()),
    ("content-type".to_owned(), "application/json".to_owned()),
]);
assert_eq!(request.body_bytes(), Some(br#"{"input":{"video":"a.mp4"}}"#.as_slice()));

Implementations§

Source§

impl Request

Source

pub fn new(method: Method, url: impl Into<String>) -> Self

A request of method to url (absolute, https:// or http://).

§Examples
use axum::http::Method;

let request = ocre::http::Request::new(Method::OPTIONS, "https://example.com/");
assert_eq!((request.method(), request.url()), ("OPTIONS", "https://example.com/"));
Source

pub fn get(url: impl Into<String>) -> Self

A GET of url.

§Examples
assert_eq!(ocre::http::Request::get("https://example.com").method(), "GET");
Source

pub fn post(url: impl Into<String>) -> Self

A POST to url.

§Examples
assert_eq!(ocre::http::Request::post("https://example.com").method(), "POST");
Source

pub fn put(url: impl Into<String>) -> Self

A PUT to url.

§Examples
assert_eq!(ocre::http::Request::put("https://example.com").method(), "PUT");
Source

pub fn patch(url: impl Into<String>) -> Self

A PATCH to url.

§Examples
assert_eq!(ocre::http::Request::patch("https://example.com").method(), "PATCH");
Source

pub fn delete(url: impl Into<String>) -> Self

A DELETE of url.

§Examples
assert_eq!(ocre::http::Request::delete("https://example.com").method(), "DELETE");
Source

pub fn head(url: impl Into<String>) -> Self

A HEAD of url.

§Examples
assert_eq!(ocre::http::Request::head("https://example.com").method(), "HEAD");
Source

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

Adds a header (the name is lowercased; a header set twice is sent twice).

§Examples
let request = ocre::http::Request::get("https://example.com").header("Accept", "text/csv");
assert_eq!(request.headers(), [("accept".to_owned(), "text/csv".to_owned())]);
Source

pub fn bearer(self, token: &str) -> Self

Adds Authorization: Bearer <token>.

§Examples
let request = ocre::http::Request::get("https://example.com").bearer("t0k");
assert_eq!(request.headers(), [("authorization".to_owned(), "Bearer t0k".to_owned())]);
Source

pub fn query(self, pairs: &[(&str, &str)]) -> Self

Appends query parameters to the URL, percent-encoded (percent_encode).

§Examples
let request = ocre::http::Request::get("https://example.com/search?page=2").query(&[("q", "a&b"), ("lang", "fr")]);
assert_eq!(request.url(), "https://example.com/search?page=2&q=a%26b&lang=fr");
Source

pub fn json(self, value: &impl Serialize) -> Self

Sends value as JSON (Content-Type: application/json).

A value that cannot be serialized (a map with non-string keys) makes send fail without sending anything.

§Examples
let request = ocre::http::Request::post("https://example.com").json(&[1, 2]);
assert_eq!(request.body_bytes(), Some(b"[1,2]".as_slice()));
Source

pub fn form(self, value: &impl Serialize) -> Self

Sends value as a form (Content-Type: application/x-www-form-urlencoded).

§Examples
let request = ocre::http::Request::post("https://example.com/token").form(&[("grant_type", "client_credentials")]);
assert_eq!(request.body_bytes(), Some(b"grant_type=client_credentials".as_slice()));
Source

pub fn body(self, bytes: impl Into<Vec<u8>>, content_type: &str) -> Self

Sends bytes as the body, with Content-Type: content_type.

§Examples
let request = ocre::http::Request::put("https://example.com/a.txt").body(b"hello".to_vec(), "text/plain");
assert_eq!(request.headers(), [("content-type".to_owned(), "text/plain".to_owned())]);
Source

pub fn timeout(self, timeout: Duration) -> Self

Gives up waiting for the answer after timeout (default DEFAULT_TIMEOUT).

§Examples
use std::time::Duration;

let request = ocre::http::Request::get("https://example.com").timeout(Duration::from_secs(5));
assert_eq!(request.timeout_duration(), Duration::from_secs(5));
Source

pub fn follow_redirects(self, follow: bool) -> Self

Whether to follow redirects (default true); with false, a 3xx is the answer.

§Examples
let request = ocre::http::Request::post("https://hooks.example.com").follow_redirects(false);
assert!(!request.follows_redirects());
Source

pub fn method(&self) -> &str

The method, uppercase.

Source

pub fn url(&self) -> &str

The URL, query parameters included.

Source

pub fn headers(&self) -> &[(String, String)]

The headers, lowercase names, in the order they were added.

Source

pub fn body_bytes(&self) -> Option<&[u8]>

The body, if any.

Source

pub fn timeout_duration(&self) -> Duration

The timeout.

Source

pub fn follows_redirects(&self) -> bool

Whether redirects are followed.

Source§

impl Request

Source

pub fn send(self) -> impl Future<Output = Result<Response>> + Send + use<>

Sends the request and returns the answer, whatever its status.

The returned future is Send: await it in a handler, a job or a scheduled task. Only runs on Workers (natively it panics, like every binding); request tests reach it through the app.

§Errors

Error::Internal (500) when the body could not be serialized, the URL or a header is invalid, the service cannot be reached, or no answer came within the timeout.

Trait Implementations§

Source§

impl Clone for Request

Source§

fn clone(&self) -> Request

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Request

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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
§

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

§

impl<T> FromRef<T> for T
where T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> 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<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
§

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

§

fn vzip(self) -> V