Skip to content

Commit

Permalink
Simplify actix-web implementations
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Feb 20, 2019
1 parent 4c4d09e commit d0d5168
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 22 deletions.
21 changes: 6 additions & 15 deletions askama/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,25 +485,16 @@ pub mod actix_web {
};
use self::mime_guess::get_mime_type;

pub fn respond<T: super::Template>(t: &T, ext: &str) -> Result<HttpResponse, Error> {
let rsp = t
.render()
.map_err(|_| ErrorInternalServerError("Template parsing error"))?;
let ctype = get_mime_type(ext).to_string();
Ok(HttpResponse::Ok().content_type(ctype.as_str()).body(rsp))
pub trait TemplateIntoResponse {
fn into_response(&self) -> Result<HttpResponse, Error>;
}

pub trait TemplateResponder {
fn responder(&self) -> Result<HttpResponse, Error>;
}

impl<T: super::Template> TemplateResponder for T {
fn responder(&self) -> Result<HttpResponse, Error> {
impl<T: super::Template> TemplateIntoResponse for T {
fn into_response(&self) -> Result<HttpResponse, Error> {
let rsp = self
.render()
.map_err(|_| ErrorInternalServerError("Template render error"))?;
let ext = T::extension().unwrap_or("txt");
let ctype = get_mime_type(ext).to_string();
.map_err(|_| ErrorInternalServerError("Template parsing error"))?;
let ctype = get_mime_type(T::extension().unwrap_or("txt")).to_string();
Ok(HttpResponse::Ok().content_type(ctype.as_str()).body(rsp))
}
}
Expand Down
7 changes: 2 additions & 5 deletions askama_derive/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,11 +234,8 @@ impl<'a> Generator<'a> {
-> ::std::result::Result<Self::Item, Self::Error> {",
);

let ext = match self.input.path.extension() {
Some(s) => s.to_str().unwrap(),
None => "txt",
};
buf.writeln(&format!("::askama::actix_web::respond(&self, {:?})", ext));
buf.writeln("use ::askama::actix_web::TemplateIntoResponse;");
buf.writeln("self.into_response()");

buf.writeln("}");
buf.writeln("}");
Expand Down
4 changes: 2 additions & 2 deletions testing/tests/actix_web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use actix_web::http::header::CONTENT_TYPE;
use actix_web::test;
use actix_web::HttpMessage;
use askama::{actix_web::TemplateResponder, Template};
use askama::{actix_web::TemplateIntoResponse, Template};
use bytes::Bytes;

#[derive(Template)]
Expand All @@ -29,7 +29,7 @@ fn test_actix_web_responder() {
let mut srv = test::TestServer::new(|app| {
app.handler(|_| {
let name = "world".to_owned();
HelloTemplate { name: &name }.responder()
HelloTemplate { name: &name }.into_response()
})
});

Expand Down

0 comments on commit d0d5168

Please sign in to comment.