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 string as the request body.

Mime

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

Examples

let uri = "https://httpbin.org/post";
let data = "hello world".to_string();
let res = surf::post(uri).body_string(data).await?;
assert_eq!(res.status(), 200);

Pass bytes as the request body.

Mime

The encoding is set to application/octet-stream.

Examples

let uri = "https://httpbin.org/post";
let data = b"hello world".to_owned();
let res = surf::post(uri).body_bytes(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?;

Return the constructed Request.

Create a Client and send the constructed Request from it.

Trait Implementations

Formats the value using the given formatter. Read more

Converts a surf::RequestBuilder to a surf::Request.

The type of value produced on completion.

Attempt to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

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

Catches panics while polling the future. Read more

Boxes the future and changes its type to dyn Future + Send + 'a. Read more

Boxes the future and changes its type to dyn Future + 'a. Read more

Returns a Future that delays execution for a specified time. Read more

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

Waits for both the future and a timeout, if the timeout completes before the future, it returns an TimeoutError. 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

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 current Span, returning an Instrumented wrapper. Read more

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

🔬 This is a nightly-only experimental API. (into_future)

The output that the future will produce on completion.

🔬 This is a nightly-only experimental API. (into_future)

Which kind of future are we turning this into?

🔬 This is a nightly-only experimental API. (into_future)

Creates a future from a value.

The type of value produced on completion.

Which kind of future are we turning this into?

Create a future from a value

Should always be Self

The type returned in the event of a conversion error.

Performs the conversion.

The type of successful values yielded by this future

The type of failures yielded by this future

Poll this TryFuture as if it were a Future. Read more

Maps this future’s success value to a different value. Read more

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

Maps this future’s Error to a new error type using the Into trait. Read more

Maps this future’s Ok to a new type using the Into trait. 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

Flatten the execution of this future when the successful result of this future is another future. Read more

Flatten the execution of this future when the successful result of this future is a stream. Read more

Unwraps this future’s output, producing a future with this future’s Ok type as its Output type. Read more

Wraps a [TryFuture] into a type that implements Future. Read more

A convenience method for calling [TryFuture::try_poll] on Unpin future types. Read more

The type returned in the event of a conversion error.

Performs the conversion.

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