1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-06-26 18:37:41 +02:00

update examples

This commit is contained in:
Nikolay Kim
2018-03-30 18:54:38 -07:00
parent 9e751de707
commit 8d8f6bedad
19 changed files with 137 additions and 104 deletions

View File

@ -4,14 +4,17 @@ extern crate env_logger;
#[macro_use]
extern crate tera;
use actix_web::*;
use actix_web::{
http, error, middleware, server,
Application, HttpRequest, HttpResponse, Error,
};
struct State {
template: tera::Tera, // <- store tera template in application state
}
fn index(req: HttpRequest<State>) -> Result<HttpResponse> {
fn index(req: HttpRequest<State>) -> Result<HttpResponse, Error> {
let s = if let Some(name) = req.query().get("name") { // <- submitted form
let mut ctx = tera::Context::new();
ctx.add("name", &name.to_owned());
@ -22,7 +25,7 @@ fn index(req: HttpRequest<State>) -> Result<HttpResponse> {
req.state().template.render("index.html", &tera::Context::new())
.map_err(|_| error::ErrorInternalServerError("Template error"))?
};
Ok(httpcodes::HTTPOk.build()
Ok(HttpResponse::Ok()
.content_type("text/html")
.body(s)?)
}
@ -32,13 +35,13 @@ fn main() {
let _ = env_logger::init();
let sys = actix::System::new("tera-example");
let addr = HttpServer::new(|| {
let _ = server::new(|| {
let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
Application::with_state(State{template: tera})
// enable logger
.middleware(middleware::Logger::default())
.resource("/", |r| r.method(Method::GET).f(index))})
.resource("/", |r| r.method(http::Method::GET).f(index))})
.bind("127.0.0.1:8080").unwrap()
.start();