[−][src]Struct fastly::response::Response
An HTTP response, including body, headers, and status code.
Sending to the client
Each execution of a Compute@Edge program may send a single response back to the client:
If no response is explicitly sent by the program, a default 200 OK response is sent.
Creation and conversion
Responses can be created programmatically:
Responses are also returned from backend requests:
For interoperability with other Rust libraries, Response can be converted to and from the
http crate's http::Response type using the From and
Into traits.
Implementations
impl Response[src]
pub fn new() -> Self[src]
Create a new Response.
The new response is created with status code 200 OK, no headers, and an empty body.
pub fn is_from_backend(&self) -> bool[src]
Return whether the response is from a backend request.
pub fn from_body(body: impl Into<Body>) -> Self[src]
Create a new Response with the given value as the body.
Argument type conversion.
See Body for details on which types can be used as a body.
Examples
let resp = Response::from_body("hello"); assert_eq!(&resp.into_body_str(), "hello");
let body_bytes: &[u8] = &[1, 2, 3]; let resp = Response::from_body(body_bytes); assert_eq!(resp.into_body_bytes().as_slice(), body_bytes);
pub fn with_body(self, body: impl Into<Body>) -> Self[src]
Builder-style equivalent of set_body().
pub fn get_body(&self) -> &Bodyⓘ[src]
Get a shared reference to the body of this response.
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_get_body(&self) -> Option<&Body>[src]
Get a shared reference to the body of this response if it has one, otherwise return
None.
pub fn get_body_mut(&mut self) -> &mut Bodyⓘ[src]
Get a mutable reference to the body of this response.
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 resp = Response::from_body("hello,"); write!(resp.get_body_mut(), " world!").unwrap(); assert_eq!(&resp.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 response if it has one, otherwise return None.
Examples
use std::io::Write; let mut resp = Response::new(); assert!(resp.try_get_body_mut().is_none()); resp.set_body("hello,"); write!(resp.try_get_body_mut().expect("body now exists"), " world!").unwrap(); assert_eq!(&resp.into_body_str(), "hello, world!");
pub fn set_body(&mut self, body: impl Into<Body>)[src]
Set the given value as the response'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ⓘ[src]
Take and return the body from this response.
After calling this method, this response 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 response if it has one, otherwise return None.
After calling this method, this response will no longer have a body.
pub fn append_body(&mut self, other: Body)[src]
Append another Body to the body of this response without reading or writing any body
contents.
If this response does not have a body, the appended body is set as the response's body.
This method should be used when combining bodies that have not necessarily been read yet,
such as a body returned from a backend response. To append contents that are already in
memory as strings or bytes, use get_body_mut() to write the
contents to the end of the body.
Examples
let mut resp = Response::from_body("hello! backend says: "); let backend_resp = Request::get("https://example.com/").send("example_backend").unwrap(); resp.append_body(backend_resp.into_body()); resp.send_to_client();
pub fn into_body_bytes(self) -> Vec<u8>[src]
Consume the response and return its body as a byte vector.
Warning
Using this method causes the entire body to be loaded into the memory of your C@E program. While this is fine for smaller bodies, larger bodies may exceed the heap limit and cause the request to fail.
When larger bodies are a possibility, you should avoid this method and instead use the
std::io::Read and std::io::BufRead methods of Body to read body contents using
controlled buffer sizes.
Examples
let resp = Response::from_body(b"hello, world!".to_vec()); let bytes = resp.into_body_bytes(); assert_eq!(&bytes, b"hello, world!");
pub fn into_body_str(self) -> String[src]
Consume the response and return its body as a string.
Warning
Using this method causes the entire body to be loaded into the memory of your C@E program. While this is fine for smaller bodies, larger bodies may exceed the heap limit and cause the request to fail.
When larger bodies are a possibility, you should avoid this method and instead use the
std::io::Read and std::io::BufRead methods of Body to read body contents using
controlled buffer sizes.
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 resp = Response::from_body("hello, world!"); let string = resp.into_body_str(); assert_eq!(&string, "hello, world!");
pub fn into_body(self) -> Bodyⓘ[src]
Consume the response 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 response and return its body if it has one, otherwise return None.
pub fn with_body_str(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 response'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 resp = Response::new(); resp.set_body_str("hello, world!"); assert_eq!(resp.get_content_type(), Some(mime::TEXT_PLAIN_UTF_8)); assert_eq!(&resp.into_body_str(), "hello, world!");
pub fn take_body_str(&mut self) -> String[src]
Take and return the body from this response as a string.
After calling this method, this response will no longer have a body.
Warning
Using this method causes the entire body to be loaded into the memory of your C@E program. While this is fine for smaller bodies, larger bodies may exceed the heap limit and cause the request to fail.
When larger bodies are a possibility, you should avoid this method and instead use the
std::io::Read and std::io::BufRead methods of Body to read body contents using
controlled buffer sizes.
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 resp = Response::from_body("hello, world!"); let string = resp.take_body_str(); assert!(resp.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 response body a line at a time.
Examples
use std::io::Write; fn remove_es(resp: &mut Response) { let mut no_es = Body::new(); for line in resp.read_body_lines() { writeln!(no_es, "{}", line.unwrap().replace("e", "")).unwrap(); } resp.set_body(no_es); }
pub fn with_body_bytes(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 response'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 resp = Response::new(); resp.set_body_bytes(b"hello, world!"); assert_eq!(resp.get_content_type(), Some(mime::APPLICATION_OCTET_STREAM)); assert_eq!(&resp.into_body_bytes(), b"hello, world!");
pub fn take_body_bytes(&mut self) -> Vec<u8>[src]
Take and return the body from this response as a string.
After calling this method, this response will no longer have a body.
Warning
Using this method causes the entire body to be loaded into the memory of your C@E program. While this is fine for smaller bodies, larger bodies may exceed the heap limit and cause the request to fail.
When larger bodies are a possibility, you should avoid this method and instead use the
std::io::Read and std::io::BufRead methods of Body to read body contents using
controlled buffer sizes.
Examples
let mut resp = Response::from_body(b"hello, world!".to_vec()); let bytes = resp.take_body_bytes(); assert!(resp.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]
&'a mut self,
chunk_size: usize
) -> impl Iterator<Item = Result<Vec<u8>, Error>> + 'a
Return an iterator that reads the response body in chunks of at most the given number of bytes.
If chunk_size does not evenly divide the length of the slice, then the last chunk will not
have length chunk_size.
Examples
fn remove_0s(resp: &mut Response) { let mut no_0s = Body::new(); for chunk in resp.read_body_chunks(4096) { let mut chunk = chunk.unwrap(); chunk.retain(|b| *b != 0); no_0s.write_bytes(&chunk); } resp.set_body(no_0s); }
pub fn with_body_json(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 response'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 resp = Response::new(); resp.set_body_json(&my_data).unwrap(); assert_eq!(resp.get_content_type(), Some(mime::APPLICATION_JSON)); assert_eq!(&resp.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 resp = Response::new(); resp.set_body_json(&my_data).unwrap(); assert_eq!(resp.get_content_type(), Some(mime::APPLICATION_JSON)); assert_eq!(&resp.into_body_str(), r#"{"count":1024,"name":"Computers"}"#);
pub fn take_body_json<T: DeserializeOwned>(&mut self) -> Result<T, Error>[src]
Take the response 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 response 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 resp = Response::from_body(r#"{"name":"Computers","count":1024}"#); let my_data = resp.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 resp = Response::from_body(r#"{"name":"Computers","count":1024}"#); let my_data = resp.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(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 response'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 resp = Response::new(); resp.set_body_form(&my_data).unwrap(); assert_eq!(resp.get_content_type(), Some(mime::APPLICATION_WWW_FORM_URLENCODED)); assert_eq!(&resp.into_body_str(), "name=Computers&count=1024");
pub fn take_body_form<T: DeserializeOwned>(&mut self) -> Result<T, Error>[src]
Take the response body and attempt to parse it as a application/x-www-form-urlencoded
formatted string.
The return type must implement serde::Deserialize without any non-static lifetimes; see
the trait documentation for details.
After calling this method, this response 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 resp = Response::from_body("name=Computers&count=1024"); let my_data = resp.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 response's
Content-Type
header, or None if that header is absent or contains an invalid MIME type.
Examples
let resp = Response::new().with_body_str("hello, world!"); assert_eq!(resp.get_content_type(), Some(mime::TEXT_PLAIN_UTF_8));
pub fn with_content_type(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 response's
Content-Type
header.
Any existing Content-Type header values will be overwritten.
Examples
let mut resp = Response::new().with_body_str("<p>hello, world!</p>"); resp.set_content_type(mime::TEXT_HTML_UTF_8);
pub fn with_header(
self,
name: impl ToHeaderName,
value: impl ToHeaderValue
) -> Self[src]
self,
name: impl ToHeaderName,
value: impl ToHeaderValue
) -> Self
Builder-style equivalent of set_header().
pub fn get_header_str<'a>(&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. 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 resp = Response::new().with_header("hello", "world!"); assert_eq!(resp.get_header_str("hello"), Some("world"));
pub fn get_header<'a>(&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. 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 resp = Response::new().with_header("hello", "world!"); assert_eq!(resp.get_header("hello"), Some(&HeaderValue::from_static("world")));
Safely handling invalid UTF-8 values:
let invalid_utf8 = &"🐈".as_bytes()[0..3]; let resp = Response::new().with_header("hello", invalid_utf8); assert_eq!(resp.get_header("hello").unwrap().as_bytes(), invalid_utf8);
pub fn get_header_all_str<'a>(&self, name: impl ToHeaderName) -> Vec<&str>[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 resp = Response::new() .with_header("hello", "world!") .with_header("hello", "universe!"); let values = resp.get_header_all_str("hello"); assert_eq!(values.len(), 2); assert!(values.contains(&"world!")); assert!(values.contains(&"universe!"));
pub fn get_header_all<'a>(
&'a self,
name: impl ToHeaderName
) -> impl Iterator<Item = &'a HeaderValue>[src]
&'a self,
name: impl ToHeaderName
) -> impl Iterator<Item = &'a HeaderValue>
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 resp = Response::new() .with_header("hello", "world!") .with_header("hello", invalid_utf8); let values: Vec<&HeaderValue> = resp.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 resp = Response::new() .with_header("hello", "world!") .with_header("hello", invalid_utf8); for value in resp.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>[src]
Get all of the response's header names as strings, or an empty vector if no headers are present.
Examples
let resp = Response::new() .with_header("hello", "world!") .with_header("goodbye", "latency!"); let names = resp.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 response's header names.
Examples
You can turn the iterator into collection, like Vec:
let resp = Response::new() .with_header("hello", "world!") .with_header("goodbye", "latency!"); let values: Vec<&HeaderName> = resp.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 resp = Response::new() .with_header("hello", "world!") .with_header("goodbye", "latency!"); for name in resp.get_header_names() { log::debug!("saw header: {:?}", name); }
pub fn set_header(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue)[src]
Set a response 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 resp = Response::new(); resp.set_header("hello", "world!"); assert_eq!(resp.get_header_str("hello"), Some("world!")); resp.set_header("hello", "universe!"); let values = resp.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]
&mut self,
name: impl ToHeaderName,
value: impl ToHeaderValue
)
Add a response 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 resp = Response::new(); resp.set_header("hello", "world!"); assert_eq!(resp.get_header_str("hello"), Some("world!")); resp.append_header("hello", "universe!"); let values = resp.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) -> bool[src]
Remove all response headers of the given name, and return whether any headers were removed.
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 resp = Response::new().with_header("hello", "world!"); assert_eq!(resp.get_header_str("hello"), Some("world!")); assert!(resp.remove_header("hello")); assert!(!resp.remove_header("not-present"));
pub fn with_status(self, status: impl ToStatusCode) -> Self[src]
Builder-style equivalent of set_status().
pub fn get_status(&self) -> StatusCode[src]
Get the HTTP status code of the response.
pub fn set_status(&mut self, status: impl ToStatusCode)[src]
Set the HTTP status code of the response.
Argument type conversion
The status code argument can be any type that implements ToStatusCode; see that trait for
details on which types can be used and when panics may arise during conversion.
Examples
Using the constants from StatusCode:
use fastly::http::StatusCode; let mut resp = Response::from_body("not found!"); resp.set_status(StatusCode::NOT_FOUND); resp.send_to_client();
Using a u16:
let mut resp = Response::from_body("not found!"); resp.set_status(404); resp.send_to_client();
pub fn with_version(self, version: Version) -> Self[src]
Builder-style equivalent of set_version().
pub fn get_version(&self) -> Version[src]
Get the HTTP version of this response.
pub fn set_version(&mut self, version: Version)[src]
Set the HTTP version of this response.
pub fn get_backend_name(&self) -> Option<&str>[src]
Get the name of the Backend this response came from, or None if the response is
synthetic.
Examples
From a backend response:
let backend_resp = Request::get("https://example.com/").send("example_backend").unwrap(); assert_eq!(backend_resp.get_backend_name(), Some("example_backend"));
From a synthetic response:
let synthetic_resp = Response::new(); assert!(synthetic_resp.get_backend_name().is_none());
pub fn get_backend(&self) -> Option<&Backend>[src]
Get the backend this response came from, or None if the response is synthetic.
Examples
From a backend response:
let backend_resp = Request::get("https://example.com/").send("example_backend").unwrap(); assert_eq!(backend_resp.get_backend(), Some(&Backend::from_name("example_backend").unwrap()));
From a synthetic response:
let synthetic_resp = Response::new(); assert!(synthetic_resp.get_backend().is_none());
pub fn get_backend_request(&self) -> Option<&Request>[src]
Get the request this response came from, or None if the response is synthetic.
Note that the returned request will only have the headers and metadata of the original request, as the body is consumed when sending the request.
This method only returns a reference to the backend request. To instead take and return the
owned request (for example, to subsequently send the request again), use
take_backend_request().
Examples
From a backend response:
let backend_resp = Request::post("https://example.com/") .with_body("hello") .send("example_backend") .unwrap(); let backend_req = backend_resp.get_backend_request().expect("response is not synthetic"); assert_eq!(backend_req.get_url_str(), "https://example.com/"); assert!(backend_req.try_get_body().is_none());
From a synthetic response:
let synthetic_resp = Response::new(); assert!(synthetic_resp.get_backend_request().is_none());
pub fn take_backend_request(&mut self) -> Option<Request>[src]
Take and return the request this response came from, or None if the response is synthetic.
Note that the returned request will only have the headers and metadata of the original request, as the body is consumed when sending the request.
Examples
From a backend response:
let mut backend_resp = Request::post("https://example.com/") .with_body("hello") .send("example_backend") .unwrap(); let backend_req = backend_resp.take_backend_request().expect("response is not synthetic"); assert_eq!(backend_req.get_url_str(), "https://example.com/"); assert!(backend_req.try_get_body().is_none()); backend_req.with_body("goodbye").send("example_backend").unwrap();
From a synthetic response:
let mut synthetic_resp = Response::new(); assert!(synthetic_resp.take_backend_request().is_none());
pub fn send_to_client(self)[src]
Begin sending the response to the client.
This method returns as soon as the response header begins sending to the client, and transmission of the response will continue in the background.
Once this method is called, nothing else may be added to the response body. To stream
additional data to a response body after it begins to send, use
stream_to_client.
Panics
This method panics if another response has already been sent to the client by this method,
by stream_to_client(), or by the equivalent methods of
ResponseHandle.
Examples
Sending a backend response without modification:
Request::get("https://example.com/").send("example_backend").unwrap().send_to_client();
Removing a header from a backend response before sending to the client:
let mut backend_resp = Request::get("https://example.com/").send("example_backend").unwrap(); backend_resp.remove_header("bad-header"); backend_resp.send_to_client();
Sending a synthetic response:
Response::from_body("hello, world!").send_to_client();
pub fn send_downstream(self)[src]
renamed to `Response::send_to_client()
pub fn stream_to_client(self) -> StreamingBodyⓘNotable traits for StreamingBody
impl Write for StreamingBody[src]
Notable traits for StreamingBody
impl Write for StreamingBodyBegin sending the response to the client, and return 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 backend response 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 response header begins sending to the client, and transmission of the response will continue in the background.
Note that the client 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.
Panics
This method panics if another response has already been sent to the client by this method,
by send_to_client(), or by the equivalent methods of
ResponseHandle.
Examples
Count the number of lines in a UTF-8 backend response body while sending it to the client:
use std::io::BufRead; let mut backend_resp = Request::get("https://example.com/").send("example_backend").unwrap(); // Take the body so we can iterate through its lines later let backend_resp_body = backend_resp.take_body(); // Start sending the backend response to the client with a now-empty body let mut client_body = backend_resp.stream_to_client(); let mut num_lines = 0; for line in backend_resp_body.lines() { let line = line.unwrap(); num_lines += 1; // Write the line to the streaming client body client_body.write_str(&line); } // Drop the streaming body to allow the client connection to close drop(client_body); log::debug!("backend response body contained {} lines", num_lines);
pub fn send_downstream_streaming(self) -> StreamingBodyⓘNotable traits for StreamingBody
impl Write for StreamingBody[src]
Notable traits for StreamingBody
impl Write for StreamingBodyrenamed to `Response::stream_to_client()
pub fn from_handles(
resp_handle: ResponseHandle,
body_handle: BodyHandle
) -> Result<Self, BufferSizeError>[src]
resp_handle: ResponseHandle,
body_handle: BodyHandle
) -> Result<Self, BufferSizeError>
Create a Response from the a ResponseHandle and a BodyHandle, returning an error
if any ResponseLimits are exceeded.
The extra metadata associated with a backend response is not tracked by the low-level handle
APIs. As a result, methods like get_backend() and
get_backend_request() will always return None for a
request created from handles.
pub fn into_handles(self) -> (ResponseHandle, BodyHandle)[src]
Create a ResponseHandle/BodyHandle pair from a Response.
The extra metadata associated with a backend response is not tracked by the low-level handle APIs. As a result, converting to handles will cause the backend and request associated with a backend response to be lost.
Trait Implementations
impl Debug for Response[src]
impl From<Response<Body>> for Response[src]
impl Into<Response<Body>> for Response[src]
Auto Trait Implementations
impl RefUnwindSafe for Response
impl Send for Response
impl Sync for Response
impl Unpin for Response
impl UnwindSafe for Response
Blanket Implementations
impl<T> Any for T where
T: 'static + ?Sized, [src]
T: 'static + ?Sized,
impl<T> Borrow<T> for T where
T: ?Sized, [src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized, [src]
T: ?Sized,
pub fn borrow_mut(&mut self) -> &mut T[src]
impl<T> From<T> for T[src]
impl<T, U> Into<U> for T where
U: From<T>, [src]
U: From<T>,
impl<T, U> TryFrom<U> for T where
U: Into<T>, [src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>, [src]
U: TryFrom<T>,