2018-04-13 03:18:42 +02:00
|
|
|
#[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
|
|
|
|
2019-03-10 07:38:15 +01:00
|
|
|
use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer};
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2019-03-10 07:38:15 +01:00
|
|
|
// store tera template in application state
|
2018-05-08 20:08:43 +02:00
|
|
|
fn index(
|
2019-03-17 04:23:09 +01:00
|
|
|
tmpl: web::Data<tera::Tera>,
|
2019-03-10 07:38:15 +01:00
|
|
|
query: web::Query<HashMap<String, String>>,
|
2018-05-08 20:08:43 +02:00
|
|
|
) -> Result<HttpResponse, Error> {
|
|
|
|
let s = if let Some(name) = query.get("name") {
|
2019-03-10 07:38:15 +01:00
|
|
|
// submitted form
|
2018-04-13 03:18:42 +02:00
|
|
|
let mut ctx = tera::Context::new();
|
2019-03-10 07:38:15 +01:00
|
|
|
ctx.insert("name", &name.to_owned());
|
|
|
|
ctx.insert("text", &"Welcome!".to_owned());
|
|
|
|
tmpl.render("user.html", &ctx)
|
2018-04-13 03:18:42 +02:00
|
|
|
.map_err(|_| error::ErrorInternalServerError("Template error"))?
|
|
|
|
} else {
|
2019-03-10 07:38:15 +01:00
|
|
|
tmpl.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
|
|
|
}
|
|
|
|
|
2019-03-10 07:38:15 +01:00
|
|
|
fn main() -> std::io::Result<()> {
|
|
|
|
std::env::set_var("RUST_LOG", "actix_web=info");
|
2018-04-13 03:18:42 +02:00
|
|
|
env_logger::init();
|
|
|
|
|
2019-03-10 07:38:15 +01:00
|
|
|
HttpServer::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
|
|
|
|
2019-03-10 07:38:15 +01:00
|
|
|
App::new()
|
2019-03-26 04:29:00 +01:00
|
|
|
.data(tera)
|
|
|
|
.wrap(middleware::Logger::default()) // enable logger
|
2019-03-10 07:38:15 +01:00
|
|
|
.service(web::resource("/").route(web::get().to(index)))
|
2019-03-10 03:03:09 +01:00
|
|
|
})
|
2019-03-10 07:38:15 +01:00
|
|
|
.bind("127.0.0.1:8080")?
|
|
|
|
.run()
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|