2018-04-13 03:18:42 +02:00
|
|
|
extern crate actix;
|
|
|
|
extern crate actix_web;
|
|
|
|
extern crate env_logger;
|
|
|
|
#[macro_use]
|
|
|
|
extern crate tera;
|
|
|
|
|
2018-05-08 20:08:43 +02:00
|
|
|
use std::collections::HashMap;
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2018-05-08 20:08:43 +02:00
|
|
|
use actix_web::{error, http, middleware, server, App, Error, HttpResponse, Query, State};
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2018-05-08 20:08:43 +02:00
|
|
|
struct AppState {
|
|
|
|
template: tera::Tera, // <- store tera template in application state
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
|
|
|
|
2018-05-08 20:08:43 +02:00
|
|
|
fn index(
|
|
|
|
state: State<AppState>, query: Query<HashMap<String, String>>,
|
|
|
|
) -> Result<HttpResponse, Error> {
|
|
|
|
let s = if let Some(name) = query.get("name") {
|
|
|
|
// <- submitted form
|
2018-04-13 03:18:42 +02:00
|
|
|
let mut ctx = tera::Context::new();
|
|
|
|
ctx.add("name", &name.to_owned());
|
|
|
|
ctx.add("text", &"Welcome!".to_owned());
|
2018-05-08 20:08:43 +02:00
|
|
|
state
|
|
|
|
.template
|
|
|
|
.render("user.html", &ctx)
|
2018-04-13 03:18:42 +02:00
|
|
|
.map_err(|_| error::ErrorInternalServerError("Template error"))?
|
|
|
|
} else {
|
2018-05-08 20:08:43 +02:00
|
|
|
state
|
|
|
|
.template
|
|
|
|
.render("index.html", &tera::Context::new())
|
2018-04-13 03:18:42 +02:00
|
|
|
.map_err(|_| error::ErrorInternalServerError("Template error"))?
|
|
|
|
};
|
2018-05-08 20:08:43 +02:00
|
|
|
Ok(HttpResponse::Ok().content_type("text/html").body(s))
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
::std::env::set_var("RUST_LOG", "actix_web=info");
|
|
|
|
env_logger::init();
|
|
|
|
let sys = actix::System::new("tera-example");
|
|
|
|
|
|
|
|
server::new(|| {
|
2018-05-08 20:08:43 +02:00
|
|
|
let tera =
|
|
|
|
compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2018-05-08 20:08:43 +02:00
|
|
|
App::with_state(AppState{template: tera})
|
2018-04-13 03:18:42 +02:00
|
|
|
// enable logger
|
|
|
|
.middleware(middleware::Logger::default())
|
2018-05-08 20:08:43 +02:00
|
|
|
.resource("/", |r| r.method(http::Method::GET).with2(index))
|
|
|
|
}).bind("127.0.0.1:8080")
|
|
|
|
.unwrap()
|
2018-04-13 03:18:42 +02:00
|
|
|
.start();
|
|
|
|
|
|
|
|
println!("Started http server: 127.0.0.1:8080");
|
|
|
|
let _ = sys.run();
|
|
|
|
}
|