1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-30 18:44:35 +01:00

use tokio::main in client example

This commit is contained in:
Rob Ede 2022-01-19 21:36:14 +00:00
parent 1cc3e7b24c
commit 1bc1538118
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
5 changed files with 39 additions and 31 deletions

View File

@ -380,34 +380,36 @@ impl HeaderIndex {
} }
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
/// Http payload item /// Chunk type yielded while decoding a payload.
pub enum PayloadItem { pub enum PayloadItem {
Chunk(Bytes), Chunk(Bytes),
Eof, Eof,
} }
/// Decoders to handle different Transfer-Encodings. /// Decoder that can handle different payload types.
/// ///
/// If a message body does not include a Transfer-Encoding, it *should* /// If a message body does not use `Transfer-Encoding`, it should include a `Content-Length`.
/// include a Content-Length header.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct PayloadDecoder { pub struct PayloadDecoder {
kind: Kind, kind: Kind,
} }
impl PayloadDecoder { impl PayloadDecoder {
/// Constructs a fixed-length payload decoder.
pub fn length(x: u64) -> PayloadDecoder { pub fn length(x: u64) -> PayloadDecoder {
PayloadDecoder { PayloadDecoder {
kind: Kind::Length(x), kind: Kind::Length(x),
} }
} }
/// Constructs a chunked encoding decoder.
pub fn chunked() -> PayloadDecoder { pub fn chunked() -> PayloadDecoder {
PayloadDecoder { PayloadDecoder {
kind: Kind::Chunked(ChunkedState::Size, 0), kind: Kind::Chunked(ChunkedState::Size, 0),
} }
} }
/// Creates an decoder that yields chunks until the stream returns EOF.
pub fn eof() -> PayloadDecoder { pub fn eof() -> PayloadDecoder {
PayloadDecoder { kind: Kind::Eof } PayloadDecoder { kind: Kind::Eof }
} }
@ -415,25 +417,26 @@ impl PayloadDecoder {
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
enum Kind { enum Kind {
/// A Reader used when a Content-Length header is passed with a positive /// A reader used when a `Content-Length` header is passed with a positive integer.
/// integer.
Length(u64), Length(u64),
/// A Reader used when Transfer-Encoding is `chunked`.
/// A reader used when `Transfer-Encoding` is `chunked`.
Chunked(ChunkedState, u64), Chunked(ChunkedState, u64),
/// A Reader used for responses that don't indicate a length or chunked.
/// A reader used for responses that don't indicate a length or chunked.
/// ///
/// Note: This should only used for `Response`s. It is illegal for a /// Note: This should only used for `Response`s. It is illegal for a `Request` to be made
/// `Request` to be made with both `Content-Length` and /// without either of `Content-Length` and `Transfer-Encoding: chunked` missing, as explained
/// `Transfer-Encoding: chunked` missing, as explained from the spec: /// in [RFC 7230 §3.3.3]:
/// ///
/// > If a Transfer-Encoding header field is present in a response and /// > If a Transfer-Encoding header field is present in a response and the chunked transfer
/// > the chunked transfer coding is not the final encoding, the /// > coding is not the final encoding, the message body length is determined by reading the
/// > message body length is determined by reading the connection until /// > connection until it is closed by the server. If a Transfer-Encoding header field is
/// > it is closed by the server. If a Transfer-Encoding header field /// > present in a request and the chunked transfer coding is not the final encoding, the
/// > is present in a request and the chunked transfer coding is not /// > message body length cannot be determined reliably; the server MUST respond with the 400
/// > the final encoding, the message body length cannot be determined /// > (Bad Request) status code and then close the connection.
/// > reliably; the server MUST respond with the 400 (Bad Request) ///
/// > status code and then close the connection. /// [RFC 7230 §3.3.3]: https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3
Eof, Eof,
} }
@ -463,6 +466,7 @@ impl Decoder for PayloadDecoder {
Ok(Some(PayloadItem::Chunk(buf))) Ok(Some(PayloadItem::Chunk(buf)))
} }
} }
Kind::Chunked(ref mut state, ref mut size) => { Kind::Chunked(ref mut state, ref mut size) => {
loop { loop {
let mut buf = None; let mut buf = None;
@ -488,6 +492,7 @@ impl Decoder for PayloadDecoder {
} }
} }
} }
Kind::Eof => { Kind::Eof => {
if src.is_empty() { if src.is_empty() {
Ok(None) Ok(None)

View File

@ -109,6 +109,7 @@ futures-util = { version = "0.3.7", default-features = false }
static_assertions = "1.1" static_assertions = "1.1"
rcgen = "0.8" rcgen = "0.8"
rustls-pemfile = "0.2" rustls-pemfile = "0.2"
tokio = { version = "1.13.1", features = ["rt-multi-thread", "macros"] }
zstd = "0.9" zstd = "0.9"
[[example]] [[example]]

View File

@ -1,13 +1,13 @@
use std::error::Error as StdError; use std::error::Error as StdError;
#[actix_web::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn StdError>> { async fn main() -> Result<(), Box<dyn StdError>> {
std::env::set_var("RUST_LOG", "client=trace,awc=trace,actix_http=trace"); env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
env_logger::init();
// construct request builder
let client = awc::Client::new(); let client = awc::Client::new();
// Create request builder, configure request and send // configure request
let request = client let request = client
.get("https://www.rust-lang.org/") .get("https://www.rust-lang.org/")
.append_header(("User-Agent", "Actix-web")); .append_header(("User-Agent", "Actix-web"));
@ -16,7 +16,7 @@ async fn main() -> Result<(), Box<dyn StdError>> {
let mut response = request.send().await?; let mut response = request.send().await?;
// server http response // server response head
println!("Response: {:?}", response); println!("Response: {:?}", response);
// read response body // read response body

View File

@ -207,7 +207,7 @@ where
self self
} }
/// Maximum supported HTTP major version. /// Sets maximum supported HTTP major version.
/// ///
/// Supported versions are HTTP/1.1 and HTTP/2. /// Supported versions are HTTP/1.1 and HTTP/2.
pub fn max_http_version(mut self, val: http::Version) -> Self { pub fn max_http_version(mut self, val: http::Version) -> Self {
@ -222,8 +222,8 @@ where
self self
} }
/// Indicates the initial window size (in octets) for /// Sets the initial window size (in octets) for HTTP/2 stream-level flow control for
/// HTTP2 stream-level flow control for received data. /// received data.
/// ///
/// The default value is 65,535 and is good for APIs, but not for big objects. /// The default value is 65,535 and is good for APIs, but not for big objects.
pub fn initial_window_size(mut self, size: u32) -> Self { pub fn initial_window_size(mut self, size: u32) -> Self {
@ -231,8 +231,8 @@ where
self self
} }
/// Indicates the initial window size (in octets) for /// Sets the initial window size (in octets) for HTTP/2 connection-level flow control for
/// HTTP2 connection-level flow control for received data. /// received data.
/// ///
/// The default value is 65,535 and is good for APIs, but not for big objects. /// The default value is 65,535 and is good for APIs, but not for big objects.
pub fn initial_connection_window_size(mut self, size: u32) -> Self { pub fn initial_connection_window_size(mut self, size: u32) -> Self {
@ -243,6 +243,7 @@ where
/// Set total number of simultaneous connections per type of scheme. /// Set total number of simultaneous connections per type of scheme.
/// ///
/// If limit is 0, the connector has no limit. /// If limit is 0, the connector has no limit.
///
/// The default limit size is 100. /// The default limit size is 100.
pub fn limit(mut self, limit: usize) -> Self { pub fn limit(mut self, limit: usize) -> Self {
self.config.limit = limit; self.config.limit = limit;

View File

@ -67,12 +67,13 @@ impl Default for Client {
} }
impl Client { impl Client {
/// Create new client instance with default settings. /// Constructs new client instance with default settings.
pub fn new() -> Client { pub fn new() -> Client {
Client::default() Client::default()
} }
/// Create `Client` builder. /// Constructs new `Client` builder.
///
/// This function is equivalent of `ClientBuilder::new()`. /// This function is equivalent of `ClientBuilder::new()`.
pub fn builder() -> ClientBuilder< pub fn builder() -> ClientBuilder<
impl Service< impl Service<