improve clarity in header setting method names

This commit is contained in:
Rob Ede 2020-09-28 00:54:49 +01:00
parent b4e02fe29a
commit c61307944d
No known key found for this signature in database
GPG Key ID: C2A3B36E841A91E6
10 changed files with 73 additions and 45 deletions

View File

@ -1,6 +1,7 @@
use crate::header::CONTENT_TYPE;
use mime::Mime; use mime::Mime;
use crate::header::CONTENT_TYPE;
header! { header! {
/// `Content-Type` header, defined in /// `Content-Type` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5) /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5)
@ -67,51 +68,51 @@ header! {
} }
impl ContentType { impl ContentType {
/// A constructor to easily create a `Content-Type: application/json` /// A constructor to easily create a `Content-Type: application/json`
/// header. /// header.
#[inline] #[inline]
pub fn json() -> ContentType { pub fn json() -> ContentType {
ContentType(mime::APPLICATION_JSON) ContentType(mime::APPLICATION_JSON)
} }
/// A constructor to easily create a `Content-Type: text/plain; /// A constructor to easily create a `Content-Type: text/plain;
/// charset=utf-8` header. /// charset=utf-8` header.
#[inline] #[inline]
pub fn plaintext() -> ContentType { pub fn plaintext() -> ContentType {
ContentType(mime::TEXT_PLAIN_UTF_8) ContentType(mime::TEXT_PLAIN_UTF_8)
} }
/// A constructor to easily create a `Content-Type: text/html` header. /// A constructor to easily create a `Content-Type: text/html` header.
#[inline] #[inline]
pub fn html() -> ContentType { pub fn html() -> ContentType {
ContentType(mime::TEXT_HTML) ContentType(mime::TEXT_HTML)
} }
/// A constructor to easily create a `Content-Type: text/xml` header. /// A constructor to easily create a `Content-Type: text/xml` header.
#[inline] #[inline]
pub fn xml() -> ContentType { pub fn xml() -> ContentType {
ContentType(mime::TEXT_XML) ContentType(mime::TEXT_XML)
} }
/// A constructor to easily create a `Content-Type: /// A constructor to easily create a `Content-Type:
/// application/www-form-url-encoded` header. /// application/www-form-url-encoded` header.
#[inline] #[inline]
pub fn form_url_encoded() -> ContentType { pub fn form_url_encoded() -> ContentType {
ContentType(mime::APPLICATION_WWW_FORM_URLENCODED) ContentType(mime::APPLICATION_WWW_FORM_URLENCODED)
} }
/// A constructor to easily create a `Content-Type: image/jpeg` header. /// A constructor to easily create a `Content-Type: image/jpeg` header.
#[inline] #[inline]
pub fn jpeg() -> ContentType { pub fn jpeg() -> ContentType {
ContentType(mime::IMAGE_JPEG) ContentType(mime::IMAGE_JPEG)
} }
/// A constructor to easily create a `Content-Type: image/png` header. /// A constructor to easily create a `Content-Type: image/png` header.
#[inline] #[inline]
pub fn png() -> ContentType { pub fn png() -> ContentType {
ContentType(mime::IMAGE_PNG) ContentType(mime::IMAGE_PNG)
} }
/// A constructor to easily create a `Content-Type: /// A constructor to easily create a `Content-Type:
/// application/octet-stream` header. /// application/octet-stream` header.
#[inline] #[inline]
pub fn octet_stream() -> ContentType { pub fn octet_stream() -> ContentType {

View File

@ -67,6 +67,7 @@ impl Header for IfRange {
fn name() -> HeaderName { fn name() -> HeaderName {
header::IF_RANGE header::IF_RANGE
} }
#[inline] #[inline]
fn parse<T>(msg: &T) -> Result<Self, ParseError> fn parse<T>(msg: &T) -> Result<Self, ParseError>
where where
@ -74,14 +75,18 @@ impl Header for IfRange {
{ {
let etag: Result<EntityTag, _> = let etag: Result<EntityTag, _> =
from_one_raw_str(msg.headers().get(&header::IF_RANGE)); from_one_raw_str(msg.headers().get(&header::IF_RANGE));
if let Ok(etag) = etag { if let Ok(etag) = etag {
return Ok(IfRange::EntityTag(etag)); return Ok(IfRange::EntityTag(etag));
} }
let date: Result<HttpDate, _> = let date: Result<HttpDate, _> =
from_one_raw_str(msg.headers().get(&header::IF_RANGE)); from_one_raw_str(msg.headers().get(&header::IF_RANGE));
if let Ok(date) = date { if let Ok(date) = date {
return Ok(IfRange::Date(date)); return Ok(IfRange::Date(date));
} }
Err(ParseError::Header) Err(ParseError::Header)
} }
} }

View File

@ -202,9 +202,6 @@ impl HeaderMap {
/// Inserts a key-value pair into the map. /// Inserts a key-value pair into the map.
/// ///
/// If the map did not previously have this key present, then `None` is
/// returned.
///
/// If the map did have this key present, the new value is associated with /// If the map did have this key present, the new value is associated with
/// the key and all previous values are removed. **Note** that only a single /// the key and all previous values are removed. **Note** that only a single
/// one of the previous values is returned. If there are multiple values /// one of the previous values is returned. If there are multiple values
@ -220,9 +217,6 @@ impl HeaderMap {
/// Inserts a key-value pair into the map. /// Inserts a key-value pair into the map.
/// ///
/// If the map did not previously have this key present, then `false` is
/// returned.
///
/// If the map did have this key present, the new value is pushed to the end /// If the map did have this key present, the new value is pushed to the end
/// of the list of values currently associated with the key. The key is not /// of the list of values currently associated with the key. The key is not
/// updated, though; this matters for types that can be `==` without being /// updated, though; this matters for types that can be `==` without being

View File

@ -354,7 +354,6 @@ impl ResponseBuilder {
/// .finish()) /// .finish())
/// } /// }
/// ``` /// ```
#[doc(hidden)]
pub fn set<H: Header>(&mut self, hdr: H) -> &mut Self { pub fn set<H: Header>(&mut self, hdr: H) -> &mut Self {
if let Some(parts) = parts(&mut self.head, &self.err) { if let Some(parts) = parts(&mut self.head, &self.err) {
match hdr.try_into() { match hdr.try_into() {
@ -367,7 +366,7 @@ impl ResponseBuilder {
self self
} }
/// Append a header to existing headers. /// Append a header to response.
/// ///
/// ```rust /// ```rust
/// use actix_http::{http, Request, Response}; /// use actix_http::{http, Request, Response};
@ -379,7 +378,7 @@ impl ResponseBuilder {
/// .finish() /// .finish()
/// } /// }
/// ``` /// ```
pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self pub fn append_header<K, V>(&mut self, key: K, value: V) -> &mut Self
where where
HeaderName: TryFrom<K>, HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>, <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
@ -399,7 +398,19 @@ impl ResponseBuilder {
self self
} }
/// Set a header. /// Append a header to response.
#[doc(hidden)]
#[deprecated = "Renamed to `append_header`."]
pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
{
self.append_header(key, value)
}
/// Set a header, overwriting any with the same key.
/// ///
/// ```rust /// ```rust
/// use actix_http::{http, Request, Response}; /// use actix_http::{http, Request, Response};
@ -411,7 +422,7 @@ impl ResponseBuilder {
/// .finish() /// .finish()
/// } /// }
/// ``` /// ```
pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self pub fn insert_header<K, V>(&mut self, key: K, value: V) -> &mut Self
where where
HeaderName: TryFrom<K>, HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>, <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
@ -431,6 +442,18 @@ impl ResponseBuilder {
self self
} }
/// Set a header, overwriting any with the same key.
#[doc(hidden)]
#[deprecated = "Renamed to `insert_header`."]
pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
{
self.insert_header(key, value)
}
/// Set the custom reason for the response. /// Set the custom reason for the response.
#[inline] #[inline]
pub fn reason(&mut self, reason: &'static str) -> &mut Self { pub fn reason(&mut self, reason: &'static str) -> &mut Self {
@ -458,7 +481,7 @@ impl ResponseBuilder {
if let Some(parts) = parts(&mut self.head, &self.err) { if let Some(parts) = parts(&mut self.head, &self.err) {
parts.set_connection_type(ConnectionType::Upgrade); parts.set_connection_type(ConnectionType::Upgrade);
} }
self.set_header(header::UPGRADE, value) self.insert_header(header::UPGRADE, value)
} }
/// Force close connection, even if it is marked as keep-alive /// Force close connection, even if it is marked as keep-alive
@ -473,7 +496,7 @@ impl ResponseBuilder {
/// Disable chunked transfer encoding for HTTP/1.1 streaming responses. /// Disable chunked transfer encoding for HTTP/1.1 streaming responses.
#[inline] #[inline]
pub fn no_chunking(&mut self, len: u64) -> &mut Self { pub fn no_chunking(&mut self, len: u64) -> &mut Self {
self.header(header::CONTENT_LENGTH, len); self.insert_header(header::CONTENT_LENGTH, len);
if let Some(parts) = parts(&mut self.head, &self.err) { if let Some(parts) = parts(&mut self.head, &self.err) {
parts.no_chunking(true); parts.no_chunking(true);
@ -556,6 +579,7 @@ impl ResponseBuilder {
/// This method calls provided closure with builder reference if value is /// This method calls provided closure with builder reference if value is
/// true. /// true.
#[deprecated = "Conditionally assign headers with standard if statement."]
pub fn if_true<F>(&mut self, value: bool, f: F) -> &mut Self pub fn if_true<F>(&mut self, value: bool, f: F) -> &mut Self
where where
F: FnOnce(&mut ResponseBuilder), F: FnOnce(&mut ResponseBuilder),
@ -568,6 +592,7 @@ impl ResponseBuilder {
/// This method calls provided closure with builder reference if value is /// This method calls provided closure with builder reference if value is
/// Some. /// Some.
#[deprecated = "Conditionally assign headers with standard if-let statement."]
pub fn if_some<T, F>(&mut self, value: Option<T>, f: F) -> &mut Self pub fn if_some<T, F>(&mut self, value: Option<T>, f: F) -> &mut Self
where where
F: FnOnce(T, &mut ResponseBuilder), F: FnOnce(T, &mut ResponseBuilder),
@ -592,10 +617,10 @@ impl ResponseBuilder {
head.extensions.borrow_mut() head.extensions.borrow_mut()
} }
#[inline]
/// Set a body and generate `Response`. /// Set a body and generate `Response`.
/// ///
/// `ResponseBuilder` can not be used after this call. /// `ResponseBuilder` can not be used after this call.
#[inline]
pub fn body<B: Into<Body>>(&mut self, body: B) -> Response { pub fn body<B: Into<Body>>(&mut self, body: B) -> Response {
self.message_body(body.into()) self.message_body(body.into())
} }
@ -626,10 +651,10 @@ impl ResponseBuilder {
} }
} }
#[inline]
/// Set a streaming body and generate `Response`. /// Set a streaming body and generate `Response`.
/// ///
/// `ResponseBuilder` can not be used after this call. /// `ResponseBuilder` can not be used after this call.
#[inline]
pub fn streaming<S, E>(&mut self, stream: S) -> Response pub fn streaming<S, E>(&mut self, stream: S) -> Response
where where
S: Stream<Item = Result<Bytes, E>> + Unpin + 'static, S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
@ -638,10 +663,10 @@ impl ResponseBuilder {
self.body(Body::from_message(BodyStream::new(stream))) self.body(Body::from_message(BodyStream::new(stream)))
} }
#[inline]
/// Set a json body and generate `Response` /// Set a json body and generate `Response`
/// ///
/// `ResponseBuilder` can not be used after this call. /// `ResponseBuilder` can not be used after this call.
#[inline]
pub fn json<T: Serialize>(&mut self, value: T) -> Response { pub fn json<T: Serialize>(&mut self, value: T) -> Response {
self.json2(&value) self.json2(&value)
} }
@ -658,7 +683,7 @@ impl ResponseBuilder {
true true
}; };
if !contains { if !contains {
self.header(header::CONTENT_TYPE, "application/json"); self.insert_header(header::CONTENT_TYPE, "application/json");
} }
self.body(Body::from(body)) self.body(Body::from(body))
@ -667,10 +692,10 @@ impl ResponseBuilder {
} }
} }
#[inline]
/// Set an empty body and generate `Response` /// Set an empty body and generate `Response`
/// ///
/// `ResponseBuilder` can not be used after this call. /// `ResponseBuilder` can not be used after this call.
#[inline]
pub fn finish(&mut self) -> Response { pub fn finish(&mut self) -> Response {
self.body(Body::Empty) self.body(Body::Empty)
} }
@ -854,8 +879,8 @@ mod tests {
#[test] #[test]
fn test_debug() { fn test_debug() {
let resp = Response::Ok() let resp = Response::Ok()
.header(COOKIE, HeaderValue::from_static("cookie1=value1; ")) .append_header(COOKIE, HeaderValue::from_static("cookie1=value1; "))
.header(COOKIE, HeaderValue::from_static("cookie2=value2; ")) .append_header(COOKIE, HeaderValue::from_static("cookie2=value2; "))
.finish(); .finish();
let dbg = format!("{:?}", resp); let dbg = format!("{:?}", resp);
assert!(dbg.contains("Response")); assert!(dbg.contains("Response"));
@ -921,7 +946,7 @@ mod tests {
#[test] #[test]
fn test_basic_builder() { fn test_basic_builder() {
let resp = Response::Ok().header("X-TEST", "value").finish(); let resp = Response::Ok().insert_header("X-TEST", "value").finish();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }

View File

@ -218,7 +218,7 @@ mod openssl {
U::InitError: fmt::Debug, U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static, <U::Service as Service>::Future: 'static,
{ {
/// Create openssl based service /// Create OpenSSL based service
pub fn openssl( pub fn openssl(
self, self,
acceptor: SslAcceptor, acceptor: SslAcceptor,
@ -280,7 +280,7 @@ mod rustls {
U::InitError: fmt::Debug, U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static, <U::Service as Service>::Future: 'static,
{ {
/// Create openssl based service /// Create Rustls based service
pub fn rustls( pub fn rustls(
self, self,
mut config: ServerConfig, mut config: ServerConfig,

View File

@ -89,7 +89,7 @@ impl ResponseError for HandshakeError {
fn error_response(&self) -> Response { fn error_response(&self) -> Response {
match *self { match *self {
HandshakeError::GetMethodRequired => Response::MethodNotAllowed() HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
.header(header::ALLOW, "GET") .insert_header(header::ALLOW, "GET")
.finish(), .finish(),
HandshakeError::NoWebsocketUpgrade => Response::BadRequest() HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
.reason("No WebSocket UPGRADE header found") .reason("No WebSocket UPGRADE header found")
@ -181,8 +181,8 @@ pub fn handshake_response(req: &RequestHead) -> ResponseBuilder {
Response::build(StatusCode::SWITCHING_PROTOCOLS) Response::build(StatusCode::SWITCHING_PROTOCOLS)
.upgrade("websocket") .upgrade("websocket")
.header(header::TRANSFER_ENCODING, "chunked") .insert_header(header::TRANSFER_ENCODING, "chunked")
.header(header::SEC_WEBSOCKET_ACCEPT, key.as_str()) .insert_header(header::SEC_WEBSOCKET_ACCEPT, key.as_str())
.take() .take()
} }

View File

@ -12,7 +12,7 @@ use flate2::Compression;
use futures_util::future::ok; use futures_util::future::ok;
use rand::Rng; use rand::Rng;
use actix_http::HttpService; use actix_http::{http::ContentEncoding, HttpService};
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{map_config, pipeline_factory}; use actix_service::{map_config, pipeline_factory};
use actix_web::dev::{AppConfig, BodyEncoding}; use actix_web::dev::{AppConfig, BodyEncoding};
@ -438,7 +438,7 @@ async fn test_client_gzip_encoding() {
let data = e.finish().unwrap(); let data = e.finish().unwrap();
HttpResponse::Ok() HttpResponse::Ok()
.header("content-encoding", "gzip") .insert_header(header::CONTENT_ENCODING, ContentEncoding::Gzip.as_str())
.body(data) .body(data)
}))) })))
}); });
@ -461,7 +461,7 @@ async fn test_client_gzip_encoding_large() {
let data = e.finish().unwrap(); let data = e.finish().unwrap();
HttpResponse::Ok() HttpResponse::Ok()
.header("content-encoding", "gzip") .insert_header(header::CONTENT_ENCODING, ContentEncoding::Gzip.as_str())
.body(data) .body(data)
}))) })))
}); });
@ -488,7 +488,7 @@ async fn test_client_gzip_encoding_large_random() {
e.write_all(&data).unwrap(); e.write_all(&data).unwrap();
let data = e.finish().unwrap(); let data = e.finish().unwrap();
HttpResponse::Ok() HttpResponse::Ok()
.header("content-encoding", "gzip") .insert_header(header::CONTENT_ENCODING, ContentEncoding::Gzip.as_str())
.body(data) .body(data)
}))) })))
}); });
@ -510,7 +510,7 @@ async fn test_client_brotli_encoding() {
e.write_all(&data).unwrap(); e.write_all(&data).unwrap();
let data = e.finish().unwrap(); let data = e.finish().unwrap();
HttpResponse::Ok() HttpResponse::Ok()
.header("content-encoding", "br") .insert_header(header::CONTENT_ENCODING, ContentEncoding::Br.as_str())
.body(data) .body(data)
}))) })))
}); });
@ -537,7 +537,7 @@ async fn test_client_brotli_encoding_large_random() {
e.write_all(&data).unwrap(); e.write_all(&data).unwrap();
let data = e.finish().unwrap(); let data = e.finish().unwrap();
HttpResponse::Ok() HttpResponse::Ok()
.header("content-encoding", "br") .insert_header(header::CONTENT_ENCODING, ContentEncoding::Br.as_str())
.body(data) .body(data)
}))) })))
}); });

View File

@ -180,8 +180,11 @@ mod tests {
let req = TestRequest::default().to_srv_request(); let req = TestRequest::default().to_srv_request();
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
ok(req ok(req.into_response(
.into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish())) HttpResponse::Ok()
.insert_header(CONTENT_TYPE, "0002")
.finish(),
))
}; };
let mut mw = DefaultHeaders::new() let mut mw = DefaultHeaders::new()
.header(CONTENT_TYPE, "0001") .header(CONTENT_TYPE, "0001")

View File

@ -522,7 +522,7 @@ mod tests {
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
ok(req.into_response( ok(req.into_response(
HttpResponse::build(StatusCode::OK) HttpResponse::build(StatusCode::OK)
.header("X-Test", "ttt") .insert_header("X-Test", "ttt")
.finish(), .finish(),
)) ))
}; };

View File

@ -626,7 +626,7 @@ mod tests {
assert!(s.contains("test=1")); assert!(s.contains("test=1"));
assert!(s.contains("x-test")); assert!(s.contains("x-test"));
let res = HttpResponse::Ok().header("x-test", "111").finish(); let res = HttpResponse::Ok().insert_header("x-test", "111").finish();
let res = TestRequest::post() let res = TestRequest::post()
.uri("/index.html?test=1") .uri("/index.html?test=1")
.to_srv_response(res); .to_srv_response(res);