Struct surf::RequestBuilder [−][src]
pub struct RequestBuilder { /* fields omitted */ }
Expand description
Request Builder
Provides an ergonomic way to chain the creation of a request.
This is generally accessed as the return value from surf::{method}()
,
however Request::builder
is also provided.
Examples
use surf::http::{Method, mime::HTML, Url};
let mut request = surf::post("https://httpbin.org/post")
.body("<html>hi</html>")
.header("custom-header", "value")
.content_type(HTML)
.build();
assert_eq!(request.take_body().into_string().await.unwrap(), "<html>hi</html>");
assert_eq!(request.method(), Method::Post);
assert_eq!(request.url(), &Url::parse("https://httpbin.org/post")?);
assert_eq!(request["custom-header"], "value");
assert_eq!(request["content-type"], "text/html;charset=utf-8");
use surf::http::{Method, Url};
let url = Url::parse("https://httpbin.org/post")?;
let request = surf::Request::builder(Method::Post, url).build();
Implementations
Create a new instance.
This method is particularly useful when input URLs might be passed by third parties, and you don’t want to panic if they’re malformed. If URLs are statically encoded, it might be easier to use one of the shorthand methods instead.
Examples
use surf::http::{Method, Url};
let url = Url::parse("https://httpbin.org/get")?;
let req = surf::RequestBuilder::new(Method::Get, url).build();
Sets a header on the request.
Examples
let req = surf::get("https://httpbin.org/get").header("header-name", "header-value").build();
assert_eq!(req["header-name"], "header-value");
Sets the Content-Type header on the request.
Examples
let req = surf::post("https://httpbin.org/post").content_type(mime::HTML).build();
assert_eq!(req["content-type"], "text/html;charset=utf-8");
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;
let mut req = surf::post("https://httpbin.org/post").body(json!({ "any": "Into<Body>"})).build();
assert_eq!(req.take_body().into_string().await.unwrap(), "{\"any\":\"Into<Body>\"}");
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 uri = "https://httpbin.org/post";
let data = &Ip { ip: "129.0.0.1".into() };
let res = surf::post(uri).body_json(data)?.await?;
assert_eq!(res.status(), 200);
Pass a file as the request body.
Mime
The encoding is set based on the file extension using mime_guess
if the operation was
successful. If path
has no extension, or its extension has no known MIME type mapping,
then None
is returned.
Errors
This method will return an error if the file couldn’t be read.
Examples
let uri = "https://httpbin.org/post";
let res = surf::post(uri).body_file("./archive.tgz").await?.await?;
assert_eq!(res.status(), 200);
Set the URL querystring.
Examples
#[derive(Serialize, Deserialize)]
struct Index {
page: u32
}
let query = Index { page: 2 };
let mut req = surf::get("https://httpbin.org/get").query(&query)?.build();
assert_eq!(req.url().query(), Some("page=2"));
assert_eq!(req.url().as_str(), "https://httpbin.org/get?page=2");
Submit the request and get the response body as bytes.
Examples
let bytes = surf::get("https://httpbin.org/get").recv_bytes().await?;
assert!(bytes.len() > 0);
Submit the request and get the response body as a string.
Examples
let string = surf::get("https://httpbin.org/get").recv_string().await?;
assert!(string.len() > 0);
Submit the request and decode the response body from json into a struct.
Examples
#[derive(Deserialize, Serialize)]
struct Ip {
ip: String
}
let uri = "https://api.ipify.org?format=json";
let Ip { ip } = surf::get(uri).recv_json().await?;
assert!(ip.len() > 10);
Submit the request and decode the response body from form encoding into a struct.
Errors
Any I/O error encountered while reading the body is immediately returned
as an Err
.
If the body cannot be interpreted as valid json for the target type T
,
an Err
is returned.
Examples
#[derive(Deserialize, Serialize)]
struct Body {
apples: u32
}
let url = "https://api.example.com/v1/response";
let Body { apples } = surf::get(url).recv_form().await?;
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
let res = surf::get("https://httpbin.org/get")
.middleware(surf::middleware::Redirect::default())
.await?;
Trait Implementations
Converts a surf::RequestBuilder
to a surf::Request
.
Auto Trait Implementations
impl !RefUnwindSafe for RequestBuilder
impl Send for RequestBuilder
impl !Sync for RequestBuilder
impl Unpin for RequestBuilder
impl !UnwindSafe for RequestBuilder
Blanket Implementations
Mutably borrows from an owned value. Read more
A convenience for calling Future::poll()
on !
Unpin
types.
Returns the result of self
or other
future, preferring self
if both are ready. Read more
Returns the result of self
or other
future, with no preference if both are ready. Read more
fn catch_unwind(self) -> CatchUnwind<Self> where
Self: UnwindSafe,
fn catch_unwind(self) -> CatchUnwind<Self> where
Self: UnwindSafe,
Catches panics while polling the future. Read more
Boxes the future and changes its type to dyn Future + Send + 'a
. Read more
Returns a Future that delays execution for a specified time. Read more
fn flatten(self) -> FlattenFuture<Self, <Self::Output as IntoFuture>::Future> where
Self::Output: IntoFuture,
fn flatten(self) -> FlattenFuture<Self, <Self::Output as IntoFuture>::Future> where
Self::Output: IntoFuture,
Flatten out the execution of this future when the result itself can be converted into another future. Read more
Waits for one of two similarly-typed futures to complete. Read more
Waits for one of two similarly-typed fallible futures to complete. Read more
Waits for two similarly-typed futures to complete. Read more
Waits for two similarly-typed fallible futures to complete. Read more
Map this future’s output to a different type, returning a new future of the resulting type. Read more
Map this future’s output to a different type, returning a new future of the resulting type. Read more
Chain on a computation for when a future finished, passing the result of
the future to the provided closure f
. Read more
Wrap this future in an Either
future, making it the left-hand variant
of that Either
. Read more
Wrap this future in an Either
future, making it the right-hand variant
of that Either
. Read more
Convert this future into a single element stream. Read more
Flatten the execution of this future when the output of this future is itself another future. Read more
Flatten the execution of this future when the successful result of this future is a stream. Read more
Fuse a future such that poll
will never again be called once it has
completed. This method can be used to turn any Future
into a
FusedFuture
. Read more
Do something with the output of a future before passing it on. Read more
Catches unwinding panics while polling the future. Read more
Create a cloneable handle to this future where all handles will resolve to the same result. Read more
Wrap the future in a Box, pinning it. Read more
Wrap the future in a Box, pinning it. Read more
Turns a Future<Output = T>
into a
TryFuture<Ok = T, Error = ()
>. Read more
Turns a Future<Output = T>
into a
TryFuture<Ok = T, Error = Never
>. Read more
A convenience for calling Future::poll
on Unpin
future types.
Evaluates and consumes the future, returning the resulting output if
the future is ready after the first call to Future::poll
. Read more
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more
into_future
)The output that the future will produce on completion.
type Future = F
type Future = F
into_future
)Which kind of future are we turning this into?
into_future
)Creates a future from a value.
type Future = T
type Future = T
Which kind of future are we turning this into?
Create a future from a value
type Output = T
type Output = T
Should always be Self
Maps this future’s success value to a different value. Read more
fn map_ok_or_else<T, E, F>(self, e: E, f: F) -> MapOkOrElse<Self, F, E> where
F: FnOnce(Self::Ok) -> T,
E: FnOnce(Self::Error) -> T,
fn map_ok_or_else<T, E, F>(self, e: E, f: F) -> MapOkOrElse<Self, F, E> where
F: FnOnce(Self::Ok) -> T,
E: FnOnce(Self::Error) -> T,
Maps this future’s success value to a different value, and permits for error handling resulting in the same type. Read more
Maps this future’s error value to a different value. Read more
Executes another future after this one resolves successfully. The success value is passed to a closure to create this subsequent future. Read more
Executes another future if this one resolves to an error. The error value is passed to a closure to create this subsequent future. Read more
Do something with the success value of a future before passing it on. Read more
Do something with the error value of a future before passing it on. Read more
fn try_flatten(self) -> TryFlatten<Self, Self::Ok> where
Self::Ok: TryFuture,
<Self::Ok as TryFuture>::Error == Self::Error,
fn try_flatten(self) -> TryFlatten<Self, Self::Ok> where
Self::Ok: TryFuture,
<Self::Ok as TryFuture>::Error == Self::Error,
Flatten the execution of this future when the successful result of this future is another future. Read more
fn try_flatten_stream(self) -> TryFlattenStream<Self> where
Self::Ok: TryStream,
<Self::Ok as TryStream>::Error == Self::Error,
fn try_flatten_stream(self) -> TryFlattenStream<Self> where
Self::Ok: TryStream,
<Self::Ok as TryStream>::Error == Self::Error,
Flatten the execution of this future when the successful result of this future is a stream. Read more
fn unwrap_or_else<F>(self, f: F) -> UnwrapOrElse<Self, F> where
F: FnOnce(Self::Error) -> Self::Ok,
fn unwrap_or_else<F>(self, f: F) -> UnwrapOrElse<Self, F> where
F: FnOnce(Self::Error) -> Self::Ok,
pub fn vzip(self) -> V
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more