improve docs for body and json

This commit is contained in:
Rob Ede 2021-12-25 02:03:40 +00:00
parent 6d239f129c
commit ca2595bf44
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
3 changed files with 72 additions and 46 deletions

View File

@ -26,20 +26,20 @@ use crate::cookie::{Cookie, CookieJar};
/// This type can be used to construct an instance of `ClientRequest` through a
/// builder-like pattern.
///
/// ```
/// #[actix_rt::main]
/// async fn main() {
/// let response = awc::Client::new()
/// .get("http://www.rust-lang.org") // <- Create request builder
/// .insert_header(("User-Agent", "Actix-web"))
/// .send() // <- Send HTTP request
/// .await;
/// ```no_run
/// # #[actix_rt::main]
/// # async fn main() {
/// let response = awc::Client::new()
/// .get("http://www.rust-lang.org") // <- Create request builder
/// .insert_header(("User-Agent", "Actix-web"))
/// .send() // <- Send HTTP request
/// .await;
///
/// response.and_then(|response| { // <- server HTTP response
/// println!("Response: {:?}", response);
/// Ok(())
/// });
/// }
/// response.and_then(|response| { // <- server HTTP response
/// println!("Response: {:?}", response);
/// Ok(())
/// });
/// # }
/// ```
pub struct ClientRequest {
pub(crate) head: RequestHead,
@ -174,17 +174,13 @@ impl ClientRequest {
/// Append a header, keeping any that were set with an equivalent field name.
///
/// ```
/// # #[actix_rt::main]
/// # async fn main() {
/// # use awc::Client;
/// use awc::http::header::CONTENT_TYPE;
/// ```no_run
/// use awc::{http::header, Client};
///
/// Client::new()
/// .get("http://www.rust-lang.org")
/// .insert_header(("X-TEST", "value"))
/// .insert_header((CONTENT_TYPE, mime::APPLICATION_JSON));
/// # }
/// .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON));
/// ```
pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self {
match header.try_into_pair() {
@ -252,23 +248,25 @@ impl ClientRequest {
/// Set a cookie
///
/// ```
/// #[actix_rt::main]
/// async fn main() {
/// let resp = awc::Client::new().get("https://www.rust-lang.org")
/// .cookie(
/// awc::cookie::Cookie::build("name", "value")
/// .domain("www.rust-lang.org")
/// .path("/")
/// .secure(true)
/// .http_only(true)
/// .finish(),
/// )
/// .send()
/// .await;
/// ```no_run
/// use awc::{cookie, Client};
///
/// println!("Response: {:?}", resp);
/// }
/// # #[actix_rt::main]
/// # async fn main() {
/// let resp = Client::new().get("https://www.rust-lang.org")
/// .cookie(
/// awc::cookie::Cookie::build("name", "value")
/// .domain("www.rust-lang.org")
/// .path("/")
/// .secure(true)
/// .http_only(true)
/// .finish(),
/// )
/// .send()
/// .await;
///
/// println!("Response: {:?}", resp);
/// # }
/// ```
#[cfg(feature = "cookies")]
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {

View File

@ -144,23 +144,53 @@ impl<S> ClientResponse<S>
where
S: Stream<Item = Result<Bytes, PayloadError>>,
{
/// Loads HTTP response's body.
/// Consumes body stream and parses JSON, resolving to a deserialized `T` value.
/// Returns a [`Future`] that consumes the body stream and resolves to [`Bytes`].
///
/// # Errors
/// `Future` implementation returns error if:
/// - content type is not `application/json`
/// - content length is greater than [limit](JsonBody::limit) (default: 2 MiB)
///
/// # Examples
/// ```no_run
/// # use awc::Client;
/// # use bytes::Bytes;
/// # #[actix_rt::main]
/// # async fn async_ctx() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::default();
/// let mut res = client.get("https://httpbin.org/robots.txt").send().await?;
/// let body: Bytes = res.body().await?;
/// # Ok(())
/// # }
/// ```
///
/// [`Future`]: std::future::Future
pub fn body(&mut self) -> ResponseBody<S> {
ResponseBody::new(self)
}
/// Consumes body stream and parses JSON, resolving to a deserialized `T` value.
/// Returns a [`Future`] consumes the body stream, parses JSON, and resolves to a deserialized
/// `T` value.
///
/// # Errors
/// Future returns error if:
/// - content type is not `application/json`;
/// - content length is greater than [limit](JsonBody::limit) (default: 2 MiB).
///
/// # Examples
/// ```no_run
/// # use awc::Client;
/// # #[actix_rt::main]
/// # async fn async_ctx() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::default();
/// let mut res = client.get("https://httpbin.org/json").send().await?;
/// let val = res.json::<serde_json::Value>().await?;
/// assert!(val.is_object());
/// # Ok(())
/// # }
/// ```
///
/// [`Future`]: std::future::Future
pub fn json<T: DeserializeOwned>(&mut self) -> JsonBody<S, T> {
JsonBody::new(self)
}

View File

@ -270,13 +270,11 @@ impl Guard for HeaderGuard {
/// ```
/// use actix_web::{web, guard::Host, App, HttpResponse};
///
/// fn main() {
/// App::new().service(
/// web::resource("/index.html")
/// .guard(Host("www.rust-lang.org"))
/// .to(|| HttpResponse::MethodNotAllowed())
/// );
/// }
/// App::new().service(
/// web::resource("/index.html")
/// .guard(Host("www.rust-lang.org"))
/// .to(|| HttpResponse::MethodNotAllowed())
/// );
/// ```
pub fn Host<H: AsRef<str>>(host: H) -> HostGuard {
HostGuard(host.as_ref().to_string(), None)