Skip to content

Commit

Permalink
use mime types in content type method
Browse files Browse the repository at this point in the history
  • Loading branch information
robjtede committed Jan 9, 2021
1 parent deaf2b0 commit f35bad5
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 25 deletions.
3 changes: 3 additions & 0 deletions actix-http/CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# Changes

## 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
Expand Down
19 changes: 9 additions & 10 deletions actix-http/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,15 +481,14 @@ impl ResponseBuilder {
self
}

/// Set response content type
/// Set response content type.
#[inline]
pub fn content_type<V>(&mut self, value: V) -> &mut Self
where
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
V: IntoHeaderValue,
{
if let Some(parts) = parts(&mut self.head, &self.err) {
match HeaderValue::try_from(value) {
match value.try_into() {
Ok(value) => {
parts.headers.insert(header::CONTENT_TYPE, value);
}
Expand Down Expand Up @@ -802,47 +801,47 @@ impl From<ResponseBuilder> for Response {
impl From<&'static str> for Response {
fn from(val: &'static str) -> Self {
Response::Ok()
.content_type("text/plain; charset=utf-8")
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
}

impl From<&'static [u8]> for Response {
fn from(val: &'static [u8]) -> Self {
Response::Ok()
.content_type("application/octet-stream")
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(val)
}
}

impl From<String> for Response {
fn from(val: String) -> Self {
Response::Ok()
.content_type("text/plain; charset=utf-8")
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
}

impl<'a> From<&'a String> for Response {
fn from(val: &'a String) -> Self {
Response::Ok()
.content_type("text/plain; charset=utf-8")
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
}

impl From<Bytes> for Response {
fn from(val: Bytes) -> Self {
Response::Ok()
.content_type("application/octet-stream")
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(val)
}
}

impl From<BytesMut> for Response {
fn from(val: BytesMut) -> Self {
Response::Ok()
.content_type("application/octet-stream")
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(val)
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
//! use actix_web::{get, web, App, HttpServer, Responder};
//!
//! #[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)
//! }
//!
Expand Down
2 changes: 1 addition & 1 deletion src/types/either.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ use crate::{
/// // respond with Right variant
/// Either::Right(
/// Ok(HttpResponse::Ok()
/// .content_type("text/html")
/// .content_type(mime::TEXT_HTML)
/// .body("<p>Hello!</p>"))
/// )
/// }
Expand Down
22 changes: 10 additions & 12 deletions src/types/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{
task::{Context, Poll},
};

use actix_http::{Error, HttpMessage, Payload};
use actix_http::Payload;
use bytes::BytesMut;
use encoding_rs::{Encoding, UTF_8};
use futures_util::{
Expand All @@ -21,13 +21,8 @@ use serde::{de::DeserializeOwned, Serialize};
#[cfg(feature = "compress")]
use crate::dev::Decompress;
use crate::{
error::UrlencodedError,
extract::FromRequest,
http::{
header::{ContentType, CONTENT_LENGTH},
StatusCode,
},
web, HttpRequest, HttpResponse, Responder,
error::UrlencodedError, extract::FromRequest, http::header::CONTENT_LENGTH, web,
Error, HttpMessage, HttpRequest, HttpResponse, Responder,
};

/// URL encoded payload extractor and responder.
Expand Down Expand Up @@ -161,8 +156,8 @@ impl<T: fmt::Display> fmt::Display for Form<T> {
impl<T: Serialize> Responder for Form<T> {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
match serde_urlencoded::to_string(&self.0) {
Ok(body) => HttpResponse::build(StatusCode::OK)
.set(ContentType::form_url_encoded())
Ok(body) => HttpResponse::Ok()
.content_type(mime::APPLICATION_WWW_FORM_URLENCODED)
.body(body),
Err(err) => HttpResponse::from_error(err.into()),
}
Expand Down Expand Up @@ -372,7 +367,10 @@ mod tests {
use serde::{Deserialize, Serialize};

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;

#[derive(Deserialize, Serialize, Debug, PartialEq)]
Expand Down Expand Up @@ -509,6 +507,6 @@ mod tests {
assert!(s.is_err());

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"));
}
}
2 changes: 1 addition & 1 deletion src/types/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ impl<T: Serialize> Responder for Json<T> {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
match serde_json::to_string(&self.0) {
Ok(body) => HttpResponse::Ok()
.content_type("application/json")
.content_type(mime::APPLICATION_JSON)
.body(body),
Err(err) => HttpResponse::from_error(err.into()),
}
Expand Down

0 comments on commit f35bad5

Please sign in to comment.