1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-06-26 15:07:42 +02:00

align remaining header map terminology (#2510)

This commit is contained in:
Rob Ede
2021-12-13 16:08:08 +00:00
committed by GitHub
parent 551a0d973c
commit 11ee8ec3ab
47 changed files with 608 additions and 503 deletions

View File

@ -2,7 +2,7 @@ use std::{convert::TryFrom, fmt, net::IpAddr, rc::Rc, time::Duration};
use actix_http::{
error::HttpError,
header::{self, HeaderMap, HeaderName},
header::{self, HeaderMap, HeaderName, TryIntoHeaderPair},
Uri,
};
use actix_rt::net::{ActixStream, TcpStream};
@ -21,11 +21,11 @@ use crate::{
/// This type can be used to construct an instance of `Client` through a
/// builder-like pattern.
pub struct ClientBuilder<S = (), M = ()> {
default_headers: bool,
max_http_version: Option<http::Version>,
stream_window_size: Option<u32>,
conn_window_size: Option<u32>,
headers: HeaderMap,
fundamental_headers: bool,
default_headers: HeaderMap,
timeout: Option<Duration>,
connector: Connector<S>,
middleware: M,
@ -44,15 +44,15 @@ impl ClientBuilder {
(),
> {
ClientBuilder {
middleware: (),
default_headers: true,
headers: HeaderMap::new(),
timeout: Some(Duration::from_secs(5)),
local_address: None,
connector: Connector::new(),
max_http_version: None,
stream_window_size: None,
conn_window_size: None,
fundamental_headers: true,
default_headers: HeaderMap::new(),
timeout: Some(Duration::from_secs(5)),
connector: Connector::new(),
middleware: (),
local_address: None,
max_redirects: 10,
}
}
@ -78,8 +78,8 @@ where
{
ClientBuilder {
middleware: self.middleware,
fundamental_headers: self.fundamental_headers,
default_headers: self.default_headers,
headers: self.headers,
timeout: self.timeout,
local_address: self.local_address,
connector,
@ -153,30 +153,46 @@ where
self
}
/// Do not add default request headers.
/// Do not add fundamental default request headers.
///
/// By default `Date` and `User-Agent` headers are set.
pub fn no_default_headers(mut self) -> Self {
self.default_headers = false;
self.fundamental_headers = false;
self
}
/// Add default header. Headers added by this method
/// get added to every request.
/// Add default header.
///
/// Headers added by this method get added to every request unless overriden by .
///
/// # Panics
/// Panics if header name or value is invalid.
pub fn add_default_header(mut self, header: impl TryIntoHeaderPair) -> Self {
match header.try_into_pair() {
Ok((key, value)) => self.default_headers.append(key, value),
Err(err) => panic!("Header error: {:?}", err.into()),
}
self
}
#[doc(hidden)]
#[deprecated(since = "3.0.0", note = "Prefer `add_default_header((key, value))`.")]
pub fn header<K, V>(mut self, key: K, value: V) -> Self
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: fmt::Debug + Into<HttpError>,
V: header::IntoHeaderValue,
V: header::TryIntoHeaderValue,
V::Error: fmt::Debug,
{
match HeaderName::try_from(key) {
Ok(key) => match value.try_into_value() {
Ok(value) => {
self.headers.append(key, value);
self.default_headers.append(key, value);
}
Err(e) => log::error!("Header value error: {:?}", e),
Err(err) => log::error!("Header value error: {:?}", err),
},
Err(e) => log::error!("Header name error: {:?}", e),
Err(err) => log::error!("Header name error: {:?}", err),
}
self
}
@ -190,10 +206,10 @@ where
Some(password) => format!("{}:{}", username, password),
None => format!("{}:", username),
};
self.header(
self.add_default_header((
header::AUTHORIZATION,
format!("Basic {}", base64::encode(&auth)),
)
))
}
/// Set client wide HTTP bearer authentication header
@ -201,13 +217,12 @@ where
where
T: fmt::Display,
{
self.header(header::AUTHORIZATION, format!("Bearer {}", token))
self.add_default_header((header::AUTHORIZATION, format!("Bearer {}", token)))
}
/// Registers middleware, in the form of a middleware component (type),
/// that runs during inbound and/or outbound processing in the request
/// life-cycle (request -> response), modifying request/response as
/// necessary, across all requests managed by the Client.
/// Registers middleware, in the form of a middleware component (type), that runs during inbound
/// and/or outbound processing in the request life-cycle (request -> response),
/// modifying request/response as necessary, across all requests managed by the `Client`.
pub fn wrap<S1, M1>(
self,
mw: M1,
@ -218,11 +233,11 @@ where
{
ClientBuilder {
middleware: NestTransform::new(self.middleware, mw),
default_headers: self.default_headers,
fundamental_headers: self.fundamental_headers,
max_http_version: self.max_http_version,
stream_window_size: self.stream_window_size,
conn_window_size: self.conn_window_size,
headers: self.headers,
default_headers: self.default_headers,
timeout: self.timeout,
connector: self.connector,
local_address: self.local_address,
@ -237,10 +252,10 @@ where
M::Transform:
Service<ConnectRequest, Response = ConnectResponse, Error = SendRequestError>,
{
let redirect_time = self.max_redirects;
let max_redirects = self.max_redirects;
if redirect_time > 0 {
self.wrap(Redirect::new().max_redirect_times(redirect_time))
if max_redirects > 0 {
self.wrap(Redirect::new().max_redirect_times(max_redirects))
._finish()
} else {
self._finish()
@ -272,7 +287,7 @@ where
let connector = boxed::rc_service(self.middleware.new_transform(connector));
Client(ClientConfig {
headers: Rc::new(self.headers),
default_headers: Rc::new(self.default_headers),
timeout: self.timeout,
connector,
})
@ -288,7 +303,7 @@ mod tests {
let client = ClientBuilder::new().basic_auth("username", Some("password"));
assert_eq!(
client
.headers
.default_headers
.get(header::AUTHORIZATION)
.unwrap()
.to_str()
@ -299,7 +314,7 @@ mod tests {
let client = ClientBuilder::new().basic_auth("username", None);
assert_eq!(
client
.headers
.default_headers
.get(header::AUTHORIZATION)
.unwrap()
.to_str()
@ -313,7 +328,7 @@ mod tests {
let client = ClientBuilder::new().bearer_auth("someS3cr3tAutht0k3n");
assert_eq!(
client
.headers
.default_headers
.get(header::AUTHORIZATION)
.unwrap()
.to_str()

View File

@ -9,7 +9,7 @@ use actix_http::{
body::{BodySize, MessageBody},
error::PayloadError,
h1,
header::{HeaderMap, IntoHeaderValue, EXPECT, HOST},
header::{HeaderMap, TryIntoHeaderValue, EXPECT, HOST},
Payload, RequestHeadType, ResponseHead, StatusCode,
};
use actix_utils::future::poll_fn;

View File

@ -6,7 +6,7 @@ use serde::Serialize;
use actix_http::{
error::HttpError,
header::{HeaderMap, HeaderName, IntoHeaderValue},
header::{HeaderMap, HeaderName, TryIntoHeaderValue},
Method, RequestHead, Uri,
};
@ -114,7 +114,7 @@ impl FrozenClientRequest {
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
V: TryIntoHeaderValue,
{
self.extra_headers(HeaderMap::new())
.extra_header(key, value)
@ -142,7 +142,7 @@ impl FrozenSendBuilder {
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
V: TryIntoHeaderValue,
{
match HeaderName::try_from(key) {
Ok(key) => match value.try_into_value() {

View File

@ -168,7 +168,7 @@ pub struct Client(ClientConfig);
#[derive(Clone)]
pub(crate) struct ClientConfig {
pub(crate) connector: BoxConnectorService,
pub(crate) headers: Rc<HeaderMap>,
pub(crate) default_headers: Rc<HeaderMap>,
pub(crate) timeout: Option<Duration>,
}
@ -204,7 +204,9 @@ impl Client {
{
let mut req = ClientRequest::new(method, url, self.0.clone());
for header in self.0.headers.iter() {
for header in self.0.default_headers.iter() {
// header map is empty
// TODO: probably append instead
req = req.insert_header_if_none(header);
}
req
@ -297,7 +299,7 @@ impl Client {
<Uri as TryFrom<U>>::Error: Into<HttpError>,
{
let mut req = ws::WebsocketsRequest::new(url, self.0.clone());
for (key, value) in self.0.headers.iter() {
for (key, value) in self.0.default_headers.iter() {
req.head.headers.insert(key.clone(), value.clone());
}
req
@ -308,6 +310,6 @@ impl Client {
/// Returns Some(&mut HeaderMap) when Client object is unique
/// (No other clone of client exists at the same time).
pub fn headers(&mut self) -> Option<&mut HeaderMap> {
Rc::get_mut(&mut self.0.headers)
Rc::get_mut(&mut self.0.default_headers)
}
}

View File

@ -442,13 +442,15 @@ mod tests {
});
let client = ClientBuilder::new()
.header("custom", "value")
.add_default_header(("custom", "value"))
.disable_redirects()
.finish();
let res = client.get(srv.url("/")).send().await.unwrap();
assert_eq!(res.status().as_u16(), 302);
let client = ClientBuilder::new().header("custom", "value").finish();
let client = ClientBuilder::new()
.add_default_header(("custom", "value"))
.finish();
let res = client.get(srv.url("/")).send().await.unwrap();
assert_eq!(res.status().as_u16(), 200);
@ -520,7 +522,7 @@ mod tests {
// send a request to different origins, http://srv1/ then http://srv2/. So it should remove the header
let client = ClientBuilder::new()
.header(header::AUTHORIZATION, "auth_key_value")
.add_default_header((header::AUTHORIZATION, "auth_key_value"))
.finish();
let res = client.get(srv1.url("/")).send().await.unwrap();
assert_eq!(res.status().as_u16(), 200);

View File

@ -6,7 +6,7 @@ use serde::Serialize;
use actix_http::{
error::HttpError,
header::{self, HeaderMap, HeaderValue, IntoHeaderPair},
header::{self, HeaderMap, HeaderValue, TryIntoHeaderPair},
ConnectionType, Method, RequestHead, Uri, Version,
};
@ -147,11 +147,8 @@ impl ClientRequest {
}
/// Insert a header, replacing any that were set with an equivalent field name.
pub fn insert_header<H>(mut self, header: H) -> Self
where
H: IntoHeaderPair,
{
match header.try_into_header_pair() {
pub fn insert_header(mut self, header: impl TryIntoHeaderPair) -> Self {
match header.try_into_pair() {
Ok((key, value)) => {
self.head.headers.insert(key, value);
}
@ -162,11 +159,8 @@ impl ClientRequest {
}
/// Insert a header only if it is not yet set.
pub fn insert_header_if_none<H>(mut self, header: H) -> Self
where
H: IntoHeaderPair,
{
match header.try_into_header_pair() {
pub fn insert_header_if_none(mut self, header: impl TryIntoHeaderPair) -> Self {
match header.try_into_pair() {
Ok((key, value)) => {
if !self.head.headers.contains_key(&key) {
self.head.headers.insert(key, value);
@ -192,11 +186,8 @@ impl ClientRequest {
/// .insert_header((CONTENT_TYPE, mime::APPLICATION_JSON));
/// # }
/// ```
pub fn append_header<H>(mut self, header: H) -> Self
where
H: IntoHeaderPair,
{
match header.try_into_header_pair() {
pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self {
match header.try_into_pair() {
Ok((key, value)) => self.head.headers.append(key, value),
Err(e) => self.err = Some(e.into()),
};
@ -588,7 +579,7 @@ mod tests {
#[actix_rt::test]
async fn test_client_header() {
let req = Client::builder()
.header(header::CONTENT_TYPE, "111")
.add_default_header((header::CONTENT_TYPE, "111"))
.finish()
.get("/");
@ -606,7 +597,7 @@ mod tests {
#[actix_rt::test]
async fn test_client_header_override() {
let req = Client::builder()
.header(header::CONTENT_TYPE, "111")
.add_default_header((header::CONTENT_TYPE, "111"))
.finish()
.get("/")
.insert_header((header::CONTENT_TYPE, "222"));

View File

@ -10,7 +10,7 @@ use std::{
use actix_http::{
body::BodyStream,
error::HttpError,
header::{self, HeaderMap, HeaderName, IntoHeaderValue},
header::{self, HeaderMap, HeaderName, TryIntoHeaderValue},
RequestHead, RequestHeadType,
};
use actix_rt::time::{sleep, Sleep};
@ -298,7 +298,7 @@ impl RequestSender {
fn set_header_if_none<V>(&mut self, key: HeaderName, value: V) -> Result<(), HttpError>
where
V: IntoHeaderValue,
V: TryIntoHeaderValue,
{
match self {
RequestSender::Owned(head) => {

View File

@ -1,6 +1,6 @@
//! Test helpers for actix http client to use during testing.
use actix_http::{h1, header::IntoHeaderPair, Payload, ResponseHead, StatusCode, Version};
use actix_http::{h1, header::TryIntoHeaderPair, Payload, ResponseHead, StatusCode, Version};
use bytes::Bytes;
#[cfg(feature = "cookies")]
@ -28,10 +28,7 @@ impl Default for TestResponse {
impl TestResponse {
/// Create TestResponse and set header
pub fn with_header<H>(header: H) -> Self
where
H: IntoHeaderPair,
{
pub fn with_header(header: impl TryIntoHeaderPair) -> Self {
Self::default().insert_header(header)
}
@ -42,11 +39,8 @@ impl TestResponse {
}
/// Insert a header
pub fn insert_header<H>(mut self, header: H) -> Self
where
H: IntoHeaderPair,
{
if let Ok((key, value)) = header.try_into_header_pair() {
pub fn insert_header(mut self, header: impl TryIntoHeaderPair) -> Self {
if let Ok((key, value)) = header.try_into_pair() {
self.head.headers.insert(key, value);
return self;
}
@ -54,11 +48,8 @@ impl TestResponse {
}
/// Append a header
pub fn append_header<H>(mut self, header: H) -> Self
where
H: IntoHeaderPair,
{
if let Ok((key, value)) = header.try_into_header_pair() {
pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self {
if let Ok((key, value)) = header.try_into_pair() {
self.head.headers.append(key, value);
return self;
}

View File

@ -39,7 +39,7 @@ use crate::{
connect::{BoxedSocket, ConnectRequest},
error::{HttpError, InvalidUrl, SendRequestError, WsClientError},
http::{
header::{self, HeaderName, HeaderValue, IntoHeaderValue, AUTHORIZATION},
header::{self, HeaderName, HeaderValue, TryIntoHeaderValue, AUTHORIZATION},
ConnectionType, Method, StatusCode, Uri, Version,
},
response::ClientResponse,
@ -171,7 +171,7 @@ impl WebsocketsRequest {
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
V: TryIntoHeaderValue,
{
match HeaderName::try_from(key) {
Ok(key) => match value.try_into_value() {
@ -190,7 +190,7 @@ impl WebsocketsRequest {
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
V: TryIntoHeaderValue,
{
match HeaderName::try_from(key) {
Ok(key) => match value.try_into_value() {
@ -209,7 +209,7 @@ impl WebsocketsRequest {
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
V: TryIntoHeaderValue,
{
match HeaderName::try_from(key) {
Ok(key) => {
@ -445,7 +445,7 @@ mod tests {
#[actix_rt::test]
async fn test_header_override() {
let req = Client::builder()
.header(header::CONTENT_TYPE, "111")
.add_default_header((header::CONTENT_TYPE, "111"))
.finish()
.ws("/")
.set_header(header::CONTENT_TYPE, "222");