[][src]Struct fastly::Request

pub struct Request { /* fields omitted */ }

An HTTP request, including body, headers, method, and URL.

Getting the client request

Call Request::from_client() to get the client request being handled by this execution of the Compute@Edge program.

Creation and conversion

New requests can be created programmatically with Request::new(). In addition, there are convenience constructors like Request::get() which automatically select the appropriate method.

For interoperability with other Rust libraries, Request can be converted to and from the http crate's http::Request type using the From and Into traits.

Sending backend requests

Requests can be sent to a backend in blocking or asynchronous fashion using send(), send_async(), or send_async_streaming().

Builder-style methods

Request can be used as a builder, allowing requests to be constructed and used through method chaining. Methods with the with_ name prefix, such as with_header(), return Self to allow chaining. The builder style is typically most useful when constructing and using a request in a single expression. For example:

Request::get("https://example.com")
    .with_header("my-header", "hello!")
    .with_header("my-other-header", "Здравствуйте!")
    .send("example_backend")?;

Setter methods

Setter methods, such as set_header(), are prefixed by set_, and can be used interchangeably with the builder-style methods, allowing you to mix and match styles based on what is most convenient for your program. Setter methods tend to work better than builder-style methods when constructing a request involves conditional branches or loops. For example:

let mut req = Request::get("https://example.com").with_header("my-header", "hello!");
if needs_translation {
    req.set_header("my-other-header", "Здравствуйте!");
}
req.send("example_backend")?;

Implementations

impl Request[src]

pub fn from_client() -> Request[src]

Get the client request being handled by this execution of the Compute@Edge program.

Panics

This method panics if the client request has already been retrieved by this method, Request::try_from_client(), or by the low-level handle API.

If the request exceeds the limits specified by RequestLimits, this method sends an empty response with a 400 BAD REQUEST HTTP status to the client, and then panics. Use try_from_client() if you want to explicitly handle these errors, for example by returning a customized error page.

pub fn try_from_client() -> Result<Request, BufferSizeError>[src]

Get the client request being handled by this execution of the Compute@Edge program, or an error if the request exceeds the limits specified by RequestLimits.

Panics

This method panics if the client request has already been retrieved by this method, Request::from_client(), or by the low-level handle API.

pub fn is_from_client(&self) -> bool[src]

Return true if this request is from the client of this execution of the Compute@Edge program.

pub fn new(method: impl ToMethod, url: impl ToUrl) -> Self[src]

Create a new request with the given method and URL, no headers, and an empty body.

Argument type conversion

The method and URL arguments can be any types that implement ToMethod and ToUrl, respectively. See those traits for details on which types can be used and when panics may arise during conversion.

pub fn clone_without_body(&self) -> Request[src]

Make a new request with the same method, url, headers, and version of this request, but no body.

If you also need to clone the request body, use clone_with_body()

Examples

let original = Request::post("https://example.com")
    .with_header("hello", "world!")
    .with_body("hello");
let new = original.clone_without_body();
assert_eq!(original.get_method(), new.get_method());
assert_eq!(original.get_url(), new.get_url());
assert_eq!(original.get_header("hello"), new.get_header("hello"));
assert_eq!(original.get_version(), new.get_version());
assert!(original.has_body());
assert!(!new.has_body());

pub fn clone_with_body(&mut self) -> Request[src]

Clone this request by reading in its body, and then writing the same body to the original and the cloned request.

This method requires mutable access to this request because reading from and writing to the body can involve an HTTP connection.

This operation is potentially expensive if the body is large. Take care when using this method on bodies with unknown sizes. Consider using methods like BufRead::lines() or Body::read_chunks() to incrementally process a body while limiting the maximum size.

Examples

let mut original = Request::post("https://example.com")
    .with_header("hello", "world!")
    .with_body("hello");
let mut new = original.clone_with_body();
assert_eq!(original.get_method(), new.get_method());
assert_eq!(original.get_url(), new.get_url());
assert_eq!(original.get_header("hello"), new.get_header("hello"));
assert_eq!(original.get_version(), new.get_version());
assert_eq!(original.take_body_bytes(), new.take_body_bytes());

pub fn get(url: impl ToUrl) -> Self[src]

Create a new GET Request with the given URL, no headers, and an empty body.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn head(url: impl ToUrl) -> Self[src]

Create a new HEAD Request with the given URL, no headers, and an empty body.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn post(url: impl ToUrl) -> Self[src]

Create a new POST Request with the given URL, no headers, and an empty body.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn put(url: impl ToUrl) -> Self[src]

Create a new PUT Request with the given URL, no headers, and an empty body.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn delete(url: impl ToUrl) -> Self[src]

Create a new DELETE Request with the given URL, no headers, and an empty body.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn connect(url: impl ToUrl) -> Self[src]

Create a new CONNECT Request with the given URL, no headers, and an empty body.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn options(url: impl ToUrl) -> Self[src]

Create a new OPTIONS Request with the given URL, no headers, and an empty body.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn trace(url: impl ToUrl) -> Self[src]

Create a new TRACE Request with the given URL, no headers, and an empty body.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn patch(url: impl ToUrl) -> Self[src]

Create a new PATCH Request with the given URL, no headers, and an empty body.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn send(self, backend: impl ToBackend) -> Result<Response, SendError>[src]

Send the request to the given backend server, and return once the response headers have been received, or an error occurs.

Argument type conversion

The backend argument can be any type that implements ToBackend; see that trait for details on which types can be used and when panics may arise during conversion.

Panics

Panics if the backend response exceeds any of the limits configured by ResponseLimits.

Examples

Sending the client request to a backend without modification:

let backend_resp = Request::from_client().send("example_backend").expect("request succeeds");
assert!(backend_resp.get_status().is_success());

Sending a synthetic request:

let backend_resp = Request::get("https://example.com")
    .send("example_backend")
    .expect("request succeeds");
assert!(backend_resp.get_status().is_success());

pub fn send_async(
    self,
    backend: impl ToBackend
) -> Result<PendingRequest, SendError>
[src]

Begin sending the request to the given backend server, and return a PendingRequest that can yield the backend response or an error.

This method returns as soon as the request begins sending to the backend, and transmission of the request body and headers will continue in the background.

This method allows for sending more than one request at once and receiving their responses in arbitrary orders. See PendingRequest for more details on how to wait on, poll, or select between pending requests.

This method is also useful for sending requests where the response is unimportant, but the request may take longer than the Compute@Edge program is able to run, as the request will continue sending even after the program that intitiated it exits.

Argument type conversion

The backend argument can be any type that implements ToBackend; see that trait for details on which types can be used and when panics may arise during conversion.

Examples

Sending a request to two backends and returning whichever response finishes first:

let backend_resp_1 = Request::get("https://example.com/")
    .send_async("example_backend_1")
    .expect("request 1 begins sending");
let backend_resp_2 = Request::get("https://example.com/")
    .send_async("example_backend_2")
    .expect("request 2 begins sending");
let (resp, _) = fastly::http::request::select(vec![backend_resp_1, backend_resp_2]);
resp.expect("request succeeds").send_to_client();

Sending a long-running request and ignoring its result so that the program can exit before it completes:

let _ = Request::post("https://example.com")
    .with_body(some_large_file)
    .send_async("example_backend");

pub fn send_async_streaming(
    self,
    backend: impl ToBackend
) -> Result<(StreamingBody, PendingRequest), SendError>
[src]

Begin sending the request to the given backend server, and return a PendingRequest that can yield the backend response or an error along with a StreamingBody that can accept further data to send.

This method is most useful for programs that do some sort of processing or inspection of a potentially-large client request body. Streaming allows the program to operate on small parts of the body rather than having to read it all into memory at once.

This method returns as soon as the request begins sending to the backend, and transmission of the request body and headers will continue in the background.

Note that the backend connection is only closed once the StreamingBody is dropped. You can explicitly drop the body once finished to avoid holding the connection open longer than necessary. The PendingRequest will not yield a Response until the StreamingBody is closed.

Examples

Count the number of lines in a UTF-8 client request body while sending it to the backend:

use std::io::BufRead;

let mut req = Request::from_client();
// Take the body so we can iterate through its lines later
let req_body = req.take_body();
// Start sending the client request to the client with a now-empty body
let (mut backend_body, pending_req) = req
    .send_async_streaming("example_backend")
    .expect("request begins sending");

let mut num_lines = 0;
for line in req_body.lines() {
    let line = line.unwrap();
    num_lines += 1;
    // Write the line to the streaming backend body
    backend_body.write_str(&line);
}
// Drop the streaming body to allow the backend connection to close
drop(backend_body);

log::debug!("client request body contained {} lines", num_lines);

pub fn with_body(mut self: Self, body: impl Into<Body>) -> Self[src]

Builder-style equivalent of set_body().

pub fn has_body(&self) -> bool[src]

Returns true if this request has a body.

pub fn get_body_mut(&mut self) -> &mut Body

Notable traits for Body

impl Read for Bodyimpl Write for Body
[src]

Get a mutable reference to the body of this request.

An empty body is returned if no body has been set, or if it has previously been returned by a method like take_body().

Examples

use std::io::Write;

let mut req = Request::post("https://example.com").with_body("hello,");
write!(req.get_body_mut(), " world!").unwrap();
assert_eq!(&req.into_body_str(), "hello, world!");

pub fn try_get_body_mut(&mut self) -> Option<&mut Body>[src]

Get a shared reference to the body of this request if it has one, otherwise return None.

Examples

use std::io::Write;

let mut req = Request::post("https://example.com");
assert!(req.try_get_body_mut().is_none());

req.set_body("hello,");
write!(req.try_get_body_mut().expect("body now exists"), " world!").unwrap();
assert_eq!(&req.into_body_str(), "hello, world!");

pub fn get_body_prefix_mut(&mut self, length: usize) -> Prefix<'_>[src]

Get a prefix of this request's body containing up to the given number of bytes.

See Body::get_prefix_mut() for details.

pub fn get_body_prefix_str_mut(&mut self, length: usize) -> PrefixString<'_>[src]

Get a prefix of this request's body as a string containing up to the given number of bytes.

See Body::get_prefix_str_mut() for details.

Panics

If the prefix contains invalid UTF-8 bytes, this function will panic. The exception to this is if the bytes are invalid because a multi-byte codepoint is cut off by the requested prefix length. In this case, the invalid bytes are left off the end of the prefix.

To explicitly handle the possibility of invalid UTF-8 bytes, use try_get_body_prefix_str_mut(), which returns an error on failure rather than panicking.

pub fn try_get_body_prefix_str_mut(
    &mut self,
    length: usize
) -> Result<PrefixString<'_>, Utf8Error>
[src]

Try to get a prefix of the body as a string containing up to the given number of bytes.

See Body::try_get_prefix_str_mut() for details.

pub fn set_body(&mut self, body: impl Into<Body>)[src]

Set the given value as the request's body.

Argument type conversion.

See Body for details on which types can be used as a body.

Any previous body that may have been set on the response is discarded. To add to an existing body, use get_body_mut() and write to the returned Body.

pub fn take_body(&mut self) -> Body

Notable traits for Body

impl Read for Bodyimpl Write for Body
[src]

Take and return the body from this request.

After calling this method, this request will no longer have a body.

An empty body is returned if no body has been set, or if it has previously been returned by a method like take_body().

pub fn try_take_body(&mut self) -> Option<Body>[src]

Take and return the body from this request if it has one, otherwise return None.

After calling this method, this request will no longer have a body.

pub fn append_body(&mut self, other: Body)[src]

Append another Body to the body of this request without reading or writing any body contents.

If this request does not have a body, the appended body is set as the request's body.

This operation is performed in amortized constant time, and so should always be preferred to reading an entire body and then writing the same contents to another body.

This method should be used when combining bodies that have not necessarily been read yet, such as the body of the client. To append contents that are already in memory as strings or bytes, you should instead use get_body_mut() to write the contents to the end of the body.

Examples

let mut req = Request::post("https://example.com").with_body("hello! client says: ");
req.append_body(Request::from_client().into_body());
req.send("example_backend").unwrap();

pub fn into_body_bytes(mut self: Self) -> Vec<u8>

Notable traits for Vec<u8, Global>

impl Write for Vec<u8, Global>
[src]

Consume the request and return its body as a byte vector.

Memory usage

This method will cause the entire body to be buffering in WebAssembly memory. You should take care not to exceed the WebAssembly memory limits, and consider using methods like read_body_lines() or read_body_chunks() to control how much of the body you process at once.

Examples

let req = Request::post("https://example.com").with_body(b"hello, world!".to_vec());
let bytes = req.into_body_bytes();
assert_eq!(&bytes, b"hello, world!");

pub fn into_body_str(mut self: Self) -> String[src]

Consume the request and return its body as a string.

Memory usage

This method will cause the entire body to be buffering in WebAssembly memory. You should take care not to exceed the WebAssembly memory limits, and consider using methods like read_body_lines() or read_body_chunks() to control how much of the body you process at once.

Panics

If the body does not contain a valid UTF-8 string, this function will panic. To explicitly handle the possibility of invalid UTF-8 data, use into_body_bytes() and then convert the bytes explicitly with a function like String::from_utf8.

Examples

let req = Request::post("https://example.com").with_body("hello, world!");
let string = req.into_body_str();
assert_eq!(&string, "hello, world!");

pub fn into_body(self) -> Body

Notable traits for Body

impl Read for Bodyimpl Write for Body
[src]

Consume the request and return its body.

An empty body is returned if no body has been set, or if it has previously been returned by a method like take_body().

pub fn try_into_body(self) -> Option<Body>[src]

Consume the request and return its body if it has one, otherwise return None.

pub fn with_body_str(mut self: Self, body: &str) -> Self[src]

Builder-style equivalent of set_body_str().

pub fn set_body_str(&mut self, body: &str)[src]

Set the given string as the request's body.

Any previous body that may have been set on the response is discarded. To add to an existing body, use get_body_mut() and write to the returned Body.

Content type

This method sets the content type to text/html; charset=utf-8.

Examples

let mut req = Request::post("https://example.com");
req.set_body_str("hello, world!");
assert_eq!(req.get_content_type(), Some(fastly::mime::TEXT_PLAIN_UTF_8));
assert_eq!(&req.into_body_str(), "hello, world!");

pub fn take_body_str(&mut self) -> String[src]

Take and return the body from this request as a string.

After calling this method, this request will no longer have a body.

Memory usage

This method will cause the entire body to be buffering in WebAssembly memory. You should take care not to exceed the WebAssembly memory limits, and consider using methods like read_body_lines() or read_body_chunks() to control how much of the body you process at once.

Panics

If the body does not contain a valid UTF-8 string, this function will panic. To handle the possibility of invalid UTF-8 data, use take_body_bytes() and then convert the bytes with a function like String::from_utf8.

Examples

let mut req = Request::post("https://example.com").with_body("hello, world!");
let string = req.take_body_str();
assert!(req.try_take_body().is_none());
assert_eq!(&string, "hello, world!");

pub fn read_body_lines(&mut self) -> Lines<&mut Body>[src]

Return a Lines iterator that reads the request body a line at a time.

Examples

use std::io::Write;

fn remove_es(req: &mut Request) {
    let mut no_es = Body::new();
    for line in req.read_body_lines() {
        writeln!(no_es, "{}", line.unwrap().replace("e", "")).unwrap();
    }
    req.set_body(no_es);
}

pub fn with_body_bytes(mut self: Self, body: &[u8]) -> Self[src]

Builder-style equivalent of set_body_bytes().

pub fn set_body_bytes(&mut self, body: &[u8])[src]

Set the given bytes as the request's body.

Any previous body that may have been set on the response is discarded. To add to an existing body, use get_body_mut() and write to the returned Body.

Content type

This method sets the content type to application/octet-stream.

Examples

let mut req = Request::post("https://example.com");
req.set_body_bytes(b"hello, world!");
assert_eq!(req.get_content_type(), Some(fastly::mime::APPLICATION_OCTET_STREAM));
assert_eq!(&req.into_body_bytes(), b"hello, world!");

pub fn take_body_bytes(&mut self) -> Vec<u8>

Notable traits for Vec<u8, Global>

impl Write for Vec<u8, Global>
[src]

Take and return the body from this request as a string.

After calling this method, this request will no longer have a body.

Memory usage

This method will cause the entire body to be buffering in WebAssembly memory. You should take care not to exceed the WebAssembly memory limits, and consider using methods like read_body_lines() or read_body_chunks() to control how much of the body you process at once.

Examples

let mut req = Request::post("https://example.com").with_body(b"hello, world!".to_vec());
let bytes = req.take_body_bytes();
assert!(req.try_take_body().is_none());
assert_eq!(&bytes, b"hello, world!");

pub fn read_body_chunks<'a>(
    &'a mut self,
    chunk_size: usize
) -> impl Iterator<Item = Result<Vec<u8>, Error>> + 'a
[src]

Return an iterator that reads the request body in chunks of at most the given number of bytes.

If chunk_size does not evenly divide the length of the body, then the last chunk will not have length chunk_size.

Examples

fn remove_0s(req: &mut Request) {
    let mut no_0s = Body::new();
    for chunk in req.read_body_chunks(4096) {
        let mut chunk = chunk.unwrap();
        chunk.retain(|b| *b != 0);
        no_0s.write_bytes(&chunk);
    }
    req.set_body(no_0s);
}

pub fn with_body_json(
    mut self: Self,
    value: &impl Serialize
) -> Result<Self, Error>
[src]

Builder-style equivalent of set_body_json().

pub fn set_body_json(&mut self, value: &impl Serialize) -> Result<(), Error>[src]

Convert the given value to JSON and set that JSON as the request's body.

The given value must implement serde::Serialize. You can either implement that trait for your own custom type, or use serde_json::Value to create untyped JSON values. See serde_json for details.

Any previous body that may have been set on the response is discarded. To add to an existing body, use get_body_mut() and write to the returned Body.

Content type

This method sets the content type to application/json.

Errors

This method returns serde_json::Error if serialization fails.

Examples

Using a type that derives serde::Serialize:

#[derive(serde::Serialize)]
struct MyData {
    name: String,
    count: u64,
}
let my_data = MyData { name: "Computers".to_string(), count: 1024 };
let mut req = Request::post("https://example.com");
req.set_body_json(&my_data).unwrap();
assert_eq!(req.get_content_type(), Some(fastly::mime::APPLICATION_JSON));
assert_eq!(&req.into_body_str(), r#"{"name":"Computers","count":1024}"#);

Using untyped JSON and the serde_json::json macro:

let my_data = serde_json::json!({
    "name": "Computers",
    "count": 1024,
});
let mut req = Request::post("https://example.com");
req.set_body_json(&my_data).unwrap();
assert_eq!(req.get_content_type(), Some(fastly::mime::APPLICATION_JSON));
assert_eq!(&req.into_body_str(), r#"{"count":1024,"name":"Computers"}"#);

pub fn take_body_json<T: DeserializeOwned>(&mut self) -> Result<T, Error>[src]

Take the request body and attempt to parse it as a JSON value.

The return type must implement serde::Deserialize without any non-static lifetimes. You can either implement that trait for your own custom type, or use serde_json::Value to deserialize untyped JSON values. See serde_json for details.

After calling this method, this request will no longer have a body.

Errors

This method returns serde_json::Error if deserialization fails.

Examples

Using a type that derives serde::de::DeserializeOwned:

#[derive(serde::Deserialize)]
struct MyData {
    name: String,
    count: u64,
}
let mut req = Request::post("https://example.com")
    .with_body(r#"{"name":"Computers","count":1024}"#);
let my_data = req.take_body_json::<MyData>().unwrap();
assert_eq!(&my_data.name, "Computers");
assert_eq!(my_data.count, 1024);

Using untyped JSON with serde_json::Value:

let my_data = serde_json::json!({
    "name": "Computers",
    "count": 1024,
});
let mut req = Request::post("https://example.com")
    .with_body(r#"{"name":"Computers","count":1024}"#);
let my_data = req.take_body_json::<serde_json::Value>().unwrap();
assert_eq!(my_data["name"].as_str(), Some("Computers"));
assert_eq!(my_data["count"].as_u64(), Some(1024));

pub fn with_body_form(
    mut self: Self,
    value: &impl Serialize
) -> Result<Self, Error>
[src]

Builder-style equivalent of set_body_form().

pub fn set_body_form(&mut self, value: &impl Serialize) -> Result<(), Error>[src]

Convert the given value to application/x-www-form-urlencoded format and set that data as the request's body.

The given value must implement serde::Serialize; see the trait documentation for details.

Any previous body that may have been set on the response is discarded. To add to an existing body, use get_body_mut() and write to the returned Body.

Content type

This method sets the content type to application/x-www-form-urlencoded.

Errors

This method returns serde_urlencoded::ser::Error if serialization fails.

Examples

#[derive(serde::Serialize)]
struct MyData {
    name: String,
    count: u64,
}
let my_data = MyData { name: "Computers".to_string(), count: 1024 };
let mut req = Request::post("https://example.com");
req.set_body_form(&my_data).unwrap();
assert_eq!(req.get_content_type(), Some(fastly::mime::APPLICATION_WWW_FORM_URLENCODED));
assert_eq!(&req.into_body_str(), "name=Computers&count=1024");

pub fn take_body_form<T: DeserializeOwned>(&mut self) -> Result<T, Error>[src]

Take the request body and attempt to parse it as a application/x-www-form-urlencoded formatted string.

The return type chosen for this function must implement serde::de::Deserialize without any non-static lifetimes; see the trait documentation for details.

After calling this method, this request will no longer have a body.

Errors

This method returns serde_urlencoded::de::Error if deserialization fails.

Examples

#[derive(serde::Deserialize)]
struct MyData {
    name: String,
    count: u64,
}
let mut req = Request::post("https://example.com").with_body("name=Computers&count=1024");
let my_data = req.take_body_form::<MyData>().unwrap();
assert_eq!(&my_data.name, "Computers");
assert_eq!(my_data.count, 1024);

pub fn get_content_type(&self) -> Option<Mime>[src]

Get the MIME type described by the request's Content-Type header, or None if that header is absent or contains an invalid MIME type.

Examples

let req = Request::post("https://example.com").with_body_str("hello, world!");
assert_eq!(req.get_content_type(), Some(fastly::mime::TEXT_PLAIN_UTF_8));

pub fn with_content_type(mut self: Self, mime: Mime) -> Self[src]

Builder-style equivalent of set_content_type().

pub fn set_content_type(&mut self, mime: Mime)[src]

Set the MIME type described by the request's Content-Type header.

Any existing Content-Type header values will be overwritten.

Examples

let mut req = Request::post("https://example.com").with_body_str("<p>hello, world!</p>");
req.set_content_type(fastly::mime::TEXT_HTML_UTF_8);

pub fn get_content_length(&self) -> Option<usize>[src]

Get the value of the request's Content-Length header, if it exists.

pub fn contains_header(&self, name: impl ToHeaderName) -> bool[src]

Returns whether the given header name is present in the request.

Argument type conversion

The header name argument can be any type that implements ToHeaderName; see that trait for details on which types can be used and when panics may arise during conversion.

Examples

let req = Request::get("https://example.com").with_header("hello", "world!");
assert!(req.contains_header("hello"));
assert!(!req.contains_header("not-present"));

pub fn with_header(
    mut self: Self,
    name: impl ToHeaderName,
    value: impl ToHeaderValue
) -> Self
[src]

Builder-style equivalent of set_header().

pub fn get_header_str(&self, name: impl ToHeaderName) -> Option<&str>[src]

Get the value of a header as a string, or None if the header is not present.

If there are multiple values for the header, only one is returned, which may be any of the values. See get_header_all_str() if you need to get all of the values.

Argument type conversion

The header name argument can be any type that implements ToHeaderName; see that trait for details on which types can be used and when panics may arise during conversion.

Panics

This method panics if the value of the header is not a valid UTF-8 string. To handle the possibility of invalid UTF-8 data, use get_header() and then convert the bytes with HeaderValue::to_str().

Examples

let req = Request::get("https://example.com").with_header("hello", "world!");
assert_eq!(req.get_header_str("hello"), Some("world"));

pub fn get_header(&self, name: impl ToHeaderName) -> Option<&HeaderValue>[src]

Get the value of a header, or None if the header is not present.

If there are multiple values for the header, only one is returned, which may be any of the values. See get_header_all() if you need to get all of the values.

Argument type conversion

The header name argument can be any type that implements ToHeaderName; see that trait for details on which types can be used and when panics may arise during conversion.

Examples

Handling UTF-8 values explicitly:

let req = Request::get("https://example.com").with_header("hello", "world!");
assert_eq!(req.get_header("hello"), Some(&HeaderValue::from_static("world")));

Safely handling invalid UTF-8 values:

let invalid_utf8 = &"🐈".as_bytes()[0..3];
let req = Request::get("https://example.com").with_header("hello", invalid_utf8);
assert_eq!(req.get_header("hello").unwrap().as_bytes(), invalid_utf8);

pub fn get_header_all_str(&self, name: impl ToHeaderName) -> Vec<&str>

Notable traits for Vec<u8, Global>

impl Write for Vec<u8, Global>
[src]

Get all values of a header as strings, or an empty vector if the header is not present.

Argument type conversion

The header name argument can be any type that implements ToHeaderName; see that trait for details on which types can be used and when panics may arise during conversion.

Panics

This method panics if any of the header values are not valid UTF-8 strings. To handle the possibility of non-UTF-8 data, use get_header_all() and then convert the bytes with HeaderValue::to_str().

Examples

let req = Request::get("https://example.com")
    .with_header("hello", "world!")
    .with_header("hello", "universe!");
let values = req.get_header_all_str("hello");
assert_eq!(values.len(), 2);
assert!(values.contains(&"world!"));
assert!(values.contains(&"universe!"));

pub fn get_header_all(
    &self,
    name: impl ToHeaderName
) -> impl Iterator<Item = &HeaderValue>
[src]

Get an iterator of all the values of a header.

Argument type conversion

The header name argument can be any type that implements ToHeaderName; see that trait for details on which types can be used and when panics may arise during conversion.

Examples

You can turn the iterator into collection, like Vec:

let invalid_utf8 = &"🐈".as_bytes()[0..3];
let req = Request::get("https://example.com")
    .with_header("hello", "world!")
    .with_header("hello", invalid_utf8);

let values: Vec<&HeaderValue> = req.get_header_all("hello").collect();
assert_eq!(values.len(), 2);
assert!(values.contains(&&HeaderValue::from_static("world!")));
assert!(values.contains(&&HeaderValue::from_bytes(invalid_utf8).unwrap()));

You can use the iterator in a loop:

let invalid_utf8 = &"🐈".as_bytes()[0..3];
let req = Request::get("https://example.com")
    .with_header("hello", "world!")
    .with_header("hello", invalid_utf8);

for value in req.get_header_all("hello") {
    if let Ok(s) = value.to_str() {
        log::debug!("hello, {}", s);
    } else {
        log::debug!("hello, invalid UTF-8!");
    }
}

pub fn get_header_names_str(&self) -> Vec<&str>

Notable traits for Vec<u8, Global>

impl Write for Vec<u8, Global>
[src]

Get all of the request's header names as strings, or an empty vector if no headers are present.

Examples

let req = Request::get("https://example.com")
    .with_header("hello", "world!")
    .with_header("goodbye", "latency!");
let names = req.get_header_names_str();
assert_eq!(names.len(), 2);
assert!(names.contains(&"hello"));
assert!(names.contains(&"goodbye"));

pub fn get_header_names(&self) -> impl Iterator<Item = &HeaderName>[src]

Get an iterator of all the request's header names.

Examples

You can turn the iterator into collection, like Vec:

let req = Request::get("https://example.com")
    .with_header("hello", "world!")
    .with_header("goodbye", "latency!");

let values: Vec<&HeaderName> = req.get_header_names().collect();
assert_eq!(values.len(), 2);
assert!(values.contains(&&HeaderName::from_static("hello")));
assert!(values.contains(&&HeaderName::from_static("goodbye")));

You can use the iterator in a loop:

let req = Request::get("https://example.com")
    .with_header("hello", "world!")
    .with_header("goodbye", "latency!");

for name in req.get_header_names() {
    log::debug!("saw header: {:?}", name);
}

pub fn set_header(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue)[src]

Set a request header to the given value, discarding any previous values for the given header name.

Argument type conversion

The header name and value arguments can be any types that implement ToHeaderName and ToHeaderValue, respectively. See those traits for details on which types can be used and when panics may arise during conversion.

Examples

let mut req = Request::get("https://example.com");

req.set_header("hello", "world!");
assert_eq!(req.get_header_str("hello"), Some("world!"));

req.set_header("hello", "universe!");

let values = req.get_header_all_str("hello");
assert_eq!(values.len(), 1);
assert!(!values.contains(&"world!"));
assert!(values.contains(&"universe!"));

pub fn append_header(
    &mut self,
    name: impl ToHeaderName,
    value: impl ToHeaderValue
)
[src]

Add a request header with given value.

Unlike set_header(), this does not discard existing values for the same header name.

Argument type conversion

The header name and value arguments can be any types that implement ToHeaderName and ToHeaderValue, respectively. See those traits for details on which types can be used and when panics may arise during conversion.

Examples

let mut req = Request::get("https://example.com");

req.set_header("hello", "world!");
assert_eq!(req.get_header_str("hello"), Some("world!"));

req.append_header("hello", "universe!");

let values = req.get_header_all_str("hello");
assert_eq!(values.len(), 2);
assert!(values.contains(&"world!"));
assert!(values.contains(&"universe!"));

pub fn remove_header(&mut self, name: impl ToHeaderName) -> Option<HeaderValue>[src]

Remove all request headers of the given name, and return one of the removed header values if any were present.

If the header has multiple values, one is returned arbitrarily. To get all of the removed header values, use get_header_all() before removing.

Argument type conversion

The header name argument can be any type that implements ToHeaderName; see that trait for details on which types can be used and when panics may arise during conversion.

Examples

let mut req = Request::get("https://example.com").with_header("hello", "world!");
assert_eq!(req.get_header_str("hello"), Some("world!"));
assert_eq!(req.remove_header("hello"), Some(HeaderValue::from_static("world!")));
assert!(req.remove_header("not-present").is_none());

pub fn remove_header_str(&mut self, name: impl ToHeaderName) -> Option<String>[src]

Remove all request headers of the given name, and return one of the removed header values as a string if any were present.

If the header has multiple values, one is returned arbitrarily. To get all of the removed header values, use get_header_all() before removing.

Argument type conversion

The header name argument can be any type that implements ToHeaderName; see that trait for details on which types can be used and when panics may arise during conversion.

Panics

This method panics if the value of the header is not a valid UTF-8 string. To handle the possibility of invalid UTF-8 data, use remove_header() and then convert the bytes with HeaderValue::to_str().

Examples

let mut req = Request::get("https://example.com").with_header("hello", "world!");
assert_eq!(req.get_header_str("hello"), Some("world!"));
assert_eq!(req.remove_header_str("hello"), Some("world!".to_string()));
assert!(req.remove_header_str("not-present").is_none());

pub fn with_method(mut self: Self, method: impl ToMethod) -> Self[src]

Builder-style equivalent of set_method().

pub fn get_method_str(&self) -> &str[src]

Get the request method as a string.

Examples

let req = Request::get("https://example.com");
assert_eq!(req.get_method_str(), "GET");

pub fn get_method(&self) -> &Method[src]

Get the request method.

Examples

use fastly::http::Method;
fn log_method(req: &Request) {
    match req.get_method() {
        &Method::GET | &Method::HEAD => log::debug!("method was a GET or HEAD"),
        &Method::POST => log::debug!("method was a POST"),
        _ => log::debug!("method was something else"),
    }
}

pub fn set_method<'a>(&mut self, method: impl ToMethod)[src]

Set the request method.

Argument type conversion

The method argument can be any type that implements ToMethod; see that trait for details on which types can be used and when panics may arise during conversion.

Examples

use fastly::http::Method;

let mut req = Request::get("https://example.com");
req.set_method(Method::POST);
assert_eq!(req.get_method(), &Method::POST);

pub fn with_url(mut self: Self, url: impl ToUrl) -> Self[src]

Builder-style equivalent of set_url().

pub fn get_url_str(&self) -> &str[src]

Get the request URL as a string.

Examples

let req = Request::get("https://example.com");
assert_eq!(req.get_url_str(), "https://example.com");

pub fn get_url(&self) -> &Url[src]

Get a shared reference to the request URL.

Examples

let req = Request::get("https://example.com/hello#world");
let url = req.get_url();
assert_eq!(url.host_str(), Some("example.com"));
assert_eq!(url.path(), "/hello");
assert_eq!(url.fragment(), Some("world"));

pub fn get_url_mut(&mut self) -> &mut Url[src]

Get a mutable reference to the request URL.

Examples

let mut req = Request::get("https://example.com/");

let url = req.get_url_mut();
url.set_path("/hello");
url.set_fragment(Some("world"));

assert_eq!(req.get_url_str(), "https://example.com/hello#world");

pub fn set_url(&mut self, url: impl ToUrl)[src]

Set the request URL.

Argument type conversion

The URL argument can be any type that implements ToUrl; see that trait for details on which types can be used and when panics may arise during conversion.

pub fn get_path(&self) -> &str[src]

Get the path component of the request URL.

Examples

let req = Request::get("https://example.com/hello#world");
assert_eq!(req.get_path(), "/hello");

pub fn with_path(mut self: Self, path: &str) -> Self[src]

Builder-style equivalent of set_path().

pub fn set_path(&mut self, path: &str)[src]

Set the path component of the request URL.

Examples

let mut req = Request::get("https://example.com/");
req.set_path("/hello");
assert_eq!(req.get_url_str(), "https://example.com/hello");

pub fn get_query_str(&self) -> Option<&str>[src]

Get the query component of the request URL, if it exists, as a percent-encoded ASCII string.

This is a shorthand for self.get_url().query(); see Url::query() for details and other query manipulation functions.

pub fn get_query<T: DeserializeOwned>(&self) -> Result<T, Error>[src]

Attempt to parse the query component of the request URL into the specified datatype.

The return type chosen for this function must implement serde::de::Deserialize without any non-static lifetimes; see the trait documentation for details.

Errors

This method returns serde_urlencoded::de::Error if deserialization fails.

Examples

Parsing into a vector of string pairs:

let req = Request::get("https://example.com/foo?hello=%F0%9F%8C%90!&bar=baz");
let pairs: Vec<(String, String)> = req.get_query().unwrap();
assert_eq!((pairs[0].0.as_str(), pairs[0].1.as_str()), ("hello", "🌐!"));

Parsing into a mapping between strings (note that duplicates are removed since HashMap is not a multimap):

use std::collections::HashMap;
let req = Request::get("https://example.com/foo?hello=%F0%9F%8C%90!&bar=baz&bar=quux");
let map: HashMap<String, String> = req.get_query().unwrap();
assert_eq!(map.len(), 2);
assert_eq!(map["hello"].as_str(), "🌐!");

Parsing into a custom type that derives serde::de::Deserialize:

#[derive(serde::Deserialize)]
struct MyData {
    name: String,
    count: u64,
}
let mut req = Request::get("https://example.com/?name=Computers&count=1024");
let my_data = req.take_body_form::<MyData>().unwrap();
assert_eq!(&my_data.name, "Computers");
assert_eq!(my_data.count, 1024);

pub fn with_query_str(mut self: Self, query: impl AsRef<str>) -> Self[src]

Builder-style equivalent of set_query_str().

pub fn set_query_str(&mut self, query: impl AsRef<str>)[src]

Set the query string of the request URL query component to the given string, performing percent-encoding if necessary.

Examples

let mut req = Request::get("https://example.com/foo");
req.set_query_str("hello=🌐!&bar=baz");
assert_eq!(req.get_url_str(), "https://example.com/foo?hello=%F0%9F%8C%90!&bar=baz");

pub fn with_query(mut self: Self, query: &impl Serialize) -> Result<Self, Error>[src]

Builder-style equivalent of set_query().

pub fn set_query(&mut self, query: &impl Serialize) -> Result<(), Error>[src]

Convert the given value to application/x-www-form-urlencoded format and set that data as the request URL query component.

The given value must implement serde::Serialize; see the trait documentation for details.

Errors

This method returns serde_urlencoded::ser::Error if serialization fails.

Examples

#[derive(serde::Serialize)]
struct MyData {
    name: String,
    count: u64,
}
let my_data = MyData { name: "Computers".to_string(), count: 1024 };
let mut req = Request::get("https://example.com/foo");
req.set_query(&my_data).unwrap();
assert_eq!(req.get_url_str(), "https://example.com/foo?name=Computers&count=1024");

pub fn remove_query(&mut self)[src]

Remove the query component from the request URL, if one exists.

Examples

let mut req = Request::get("https://example.com/foo?hello=%F0%9F%8C%90!&bar=baz");
req.remove_query();
assert_eq!(req.get_url_str(), "https://example.com/foo");

pub fn with_version(mut self: Self, version: Version) -> Self[src]

Builder-style equivalent of set_version().

pub fn get_version(&self) -> Version[src]

Get the HTTP version of this request.

pub fn set_version(&mut self, version: Version)[src]

Set the HTTP version of this request.

pub fn with_pass(mut self: Self, pass: bool) -> Self[src]

Builder-style equivalent of set_pass().

pub fn set_pass(&mut self, pass: bool)[src]

Set whether this request should be cached if sent to a backend.

By default this is false, which means the backend will only be reached if a cached response is not available. Set this to true to send the request directly to the backend without caching.

Overrides

Setting this to true overrides any other custom caching behaviors for this request, such as Request::set_ttl() or Request::set_surrogate_key().

pub fn with_ttl(mut self: Self, ttl: u32) -> Self[src]

Builder-style equivalent of set_ttl().

pub fn set_ttl(&mut self, ttl: u32)[src]

Override the caching behavior of this request to use the given Time to Live (TTL), in seconds.

Overrides

This overrides the behavior specified in the response headers, and sets the pass behavior to false.

pub fn with_stale_while_revalidate(mut self: Self, swr: u32) -> Self[src]

Builder-style equivalent of set_stale_while_revalidate().

pub fn set_stale_while_revalidate(&mut self, swr: u32)[src]

Override the caching behavior of this request to use the given stale-while-revalidate time, in seconds.

Overrides

This overrides the behavior specified in the response headers, and sets the pass behavior to false.

pub fn with_pci(mut self: Self, pci: bool) -> Self[src]

Builder-style equivalent of set_pci().

pub fn set_pci(&mut self, pci: bool)[src]

Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching.

By default, this is false, which means the request may not be PCI/HIPAA-compliant. Set it to true to enable compliant caching.

See the Fastly PCI-Compliant Caching and Delivery documentation for details.

Overrides

This sets the pass behavior to false.

pub fn with_surrogate_key(mut self: Self, sk: HeaderValue) -> Self[src]

Builder-style equivalent of set_surrogate_key().

pub fn set_surrogate_key(&mut self, sk: HeaderValue)[src]

Override the caching behavior of this request to include the given surrogate key, provided as a header value.

See the Fastly surrogate keys guide for details.

Overrides

This sets the pass behavior to false, and extends (but does not replace) any Surrogate-Key response headers from the backend.

pub fn get_client_ip_addr(&self) -> Option<IpAddr>[src]

Returns the IP address of the client making the HTTP request.

Returns None if this is not the client request.

pub fn get_original_header_names(&self) -> Option<impl Iterator<Item = String>>[src]

Returns the client request's header names exactly as they were originally received.

This includes both the original character cases, as well as the original order of the received headers.

Returns None if this is not the client request.

pub fn get_original_header_count(&self) -> Option<u32>[src]

Returns the number of headers in the client request as originally received.

Returns None if this is not the client request.

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

Get the raw bytes sent by the client in the TLS ClientHello message.

See RFC 5246 for details.

Returns None if this is not the client request.

pub fn get_tls_cipher_openssl_name(&self) -> Option<&'static str>[src]

Get the cipher suite used to secure the client TLS connection.

The value returned will be consistent with the OpenSSL name for the cipher suite.

Returns None if this is not the client request.

Examples

assert_eq!(Request::from_client().get_tls_cipher_openssl_name().unwrap(), "ECDHE-RSA-AES128-GCM-SHA256");

pub fn get_tls_protocol(&self) -> Option<&'static str>[src]

Get the TLS protocol version used to secure the client TLS connection.

Returns None if this is not the client request.

Examples

assert_eq!(Request::from_client().get_tls_protocol().unwrap(), "TLSv1.2");

pub fn from_handles(
    req_handle: RequestHandle,
    body_handle: Option<BodyHandle>
) -> Result<Self, BufferSizeError>
[src]

Create a Request from the low-level handle API.

Errors

This conversion can fail if the request exceeds the limits specified by RequestLimits.

pub fn into_handles(mut self: Self) -> (RequestHandle, Option<BodyHandle>)[src]

Convert a Request into the low-level handle API.

Trait Implementations

impl Debug for Request[src]

impl From<Request<Body>> for Request[src]

impl Into<Request<Body>> for Request[src]

Auto Trait Implementations

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.