use mime types in content type method

This commit is contained in:
Rob Ede 2021-01-09 05:56:16 +00:00
parent 6fa1eddb6a
commit 9f65271f73
No known key found for this signature in database
GPG Key ID: C2A3B36E841A91E6
6 changed files with 26 additions and 25 deletions

View File

@ -1,6 +1,9 @@
# Changes # Changes
## Unreleased - 2021-xx-xx ## Unreleased - 2021-xx-xx
* `Response::content_type` now takes an `impl IntoHeaderValue` to support `mime` types. [#????]
[#????]: https://github.com/actix/actix-web/pull/????
## 3.0.0-beta.1 - 2021-01-07 ## 3.0.0-beta.1 - 2021-01-07

View File

@ -481,15 +481,14 @@ impl ResponseBuilder {
self self
} }
/// Set response content type /// Set response content type.
#[inline] #[inline]
pub fn content_type<V>(&mut self, value: V) -> &mut Self pub fn content_type<V>(&mut self, value: V) -> &mut Self
where where
HeaderValue: TryFrom<V>, V: IntoHeaderValue,
<HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
{ {
if let Some(parts) = parts(&mut self.head, &self.err) { if let Some(parts) = parts(&mut self.head, &self.err) {
match HeaderValue::try_from(value) { match value.try_into() {
Ok(value) => { Ok(value) => {
parts.headers.insert(header::CONTENT_TYPE, value); parts.headers.insert(header::CONTENT_TYPE, value);
} }
@ -802,7 +801,7 @@ impl From<ResponseBuilder> for Response {
impl From<&'static str> for Response { impl From<&'static str> for Response {
fn from(val: &'static str) -> Self { fn from(val: &'static str) -> Self {
Response::Ok() Response::Ok()
.content_type("text/plain; charset=utf-8") .content_type(mime::TEXT_PLAIN_UTF_8)
.body(val) .body(val)
} }
} }
@ -810,7 +809,7 @@ impl From<&'static str> for Response {
impl From<&'static [u8]> for Response { impl From<&'static [u8]> for Response {
fn from(val: &'static [u8]) -> Self { fn from(val: &'static [u8]) -> Self {
Response::Ok() Response::Ok()
.content_type("application/octet-stream") .content_type(mime::APPLICATION_OCTET_STREAM)
.body(val) .body(val)
} }
} }
@ -818,7 +817,7 @@ impl From<&'static [u8]> for Response {
impl From<String> for Response { impl From<String> for Response {
fn from(val: String) -> Self { fn from(val: String) -> Self {
Response::Ok() Response::Ok()
.content_type("text/plain; charset=utf-8") .content_type(mime::TEXT_PLAIN_UTF_8)
.body(val) .body(val)
} }
} }
@ -826,7 +825,7 @@ impl From<String> for Response {
impl<'a> From<&'a String> for Response { impl<'a> From<&'a String> for Response {
fn from(val: &'a String) -> Self { fn from(val: &'a String) -> Self {
Response::Ok() Response::Ok()
.content_type("text/plain; charset=utf-8") .content_type(mime::TEXT_PLAIN_UTF_8)
.body(val) .body(val)
} }
} }
@ -834,7 +833,7 @@ impl<'a> From<&'a String> for Response {
impl From<Bytes> for Response { impl From<Bytes> for Response {
fn from(val: Bytes) -> Self { fn from(val: Bytes) -> Self {
Response::Ok() Response::Ok()
.content_type("application/octet-stream") .content_type(mime::APPLICATION_OCTET_STREAM)
.body(val) .body(val)
} }
} }
@ -842,7 +841,7 @@ impl From<Bytes> for Response {
impl From<BytesMut> for Response { impl From<BytesMut> for Response {
fn from(val: BytesMut) -> Self { fn from(val: BytesMut) -> Self {
Response::Ok() Response::Ok()
.content_type("application/octet-stream") .content_type(mime::APPLICATION_OCTET_STREAM)
.body(val) .body(val)
} }
} }

View File

@ -6,7 +6,8 @@
//! use actix_web::{get, web, App, HttpServer, Responder}; //! use actix_web::{get, web, App, HttpServer, Responder};
//! //!
//! #[get("/{id}/{name}/index.html")] //! #[get("/{id}/{name}/index.html")]
//! async fn index(web::Path((id, name)): web::Path<(u32, String)>) -> impl Responder { //! async fn index(path: web::Path<(u32, String)>) -> impl Responder {
//! let (id, name) = path.into_inner();
//! format!("Hello {}! id:{}", name, id) //! format!("Hello {}! id:{}", name, id)
//! } //! }
//! //!

View File

@ -61,7 +61,7 @@ use crate::{
/// // respond with Right variant /// // respond with Right variant
/// Either::Right( /// Either::Right(
/// Ok(HttpResponse::Ok() /// Ok(HttpResponse::Ok()
/// .content_type("text/html") /// .content_type(mime::TEXT_HTML)
/// .body("<p>Hello!</p>")) /// .body("<p>Hello!</p>"))
/// ) /// )
/// } /// }

View File

@ -9,7 +9,7 @@ use std::{
task::{Context, Poll}, task::{Context, Poll},
}; };
use actix_http::{Error, HttpMessage, Payload}; use actix_http::Payload;
use bytes::BytesMut; use bytes::BytesMut;
use encoding_rs::{Encoding, UTF_8}; use encoding_rs::{Encoding, UTF_8};
use futures_util::{ use futures_util::{
@ -21,13 +21,8 @@ use serde::{de::DeserializeOwned, Serialize};
#[cfg(feature = "compress")] #[cfg(feature = "compress")]
use crate::dev::Decompress; use crate::dev::Decompress;
use crate::{ use crate::{
error::UrlencodedError, error::UrlencodedError, extract::FromRequest, http::header::CONTENT_LENGTH, web,
extract::FromRequest, Error, HttpMessage, HttpRequest, HttpResponse, Responder,
http::{
header::{ContentType, CONTENT_LENGTH},
StatusCode,
},
web, HttpRequest, HttpResponse, Responder,
}; };
/// URL encoded payload extractor and responder. /// URL encoded payload extractor and responder.
@ -161,8 +156,8 @@ impl<T: fmt::Display> fmt::Display for Form<T> {
impl<T: Serialize> Responder for Form<T> { impl<T: Serialize> Responder for Form<T> {
fn respond_to(self, _: &HttpRequest) -> HttpResponse { fn respond_to(self, _: &HttpRequest) -> HttpResponse {
match serde_urlencoded::to_string(&self.0) { match serde_urlencoded::to_string(&self.0) {
Ok(body) => HttpResponse::build(StatusCode::OK) Ok(body) => HttpResponse::Ok()
.set(ContentType::form_url_encoded()) .content_type(mime::APPLICATION_WWW_FORM_URLENCODED)
.body(body), .body(body),
Err(err) => HttpResponse::from_error(err.into()), Err(err) => HttpResponse::from_error(err.into()),
} }
@ -372,7 +367,10 @@ mod tests {
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use super::*; use super::*;
use crate::http::header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE}; use crate::http::{
header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE},
StatusCode,
};
use crate::test::TestRequest; use crate::test::TestRequest;
#[derive(Deserialize, Serialize, Debug, PartialEq)] #[derive(Deserialize, Serialize, Debug, PartialEq)]
@ -509,6 +507,6 @@ mod tests {
assert!(s.is_err()); assert!(s.is_err());
let err_str = s.err().unwrap().to_string(); let err_str = s.err().unwrap().to_string();
assert!(err_str.contains("Urlencoded payload size is bigger")); assert!(err_str.starts_with("URL encoded payload is larger"));
} }
} }

View File

@ -121,7 +121,7 @@ impl<T: Serialize> Responder for Json<T> {
fn respond_to(self, _: &HttpRequest) -> HttpResponse { fn respond_to(self, _: &HttpRequest) -> HttpResponse {
match serde_json::to_string(&self.0) { match serde_json::to_string(&self.0) {
Ok(body) => HttpResponse::Ok() Ok(body) => HttpResponse::Ok()
.content_type("application/json") .content_type(mime::APPLICATION_JSON)
.body(body), .body(body),
Err(err) => HttpResponse::from_error(err.into()), Err(err) => HttpResponse::from_error(err.into()),
} }