2020-09-10 22:34:32 +02:00
|
|
|
use std::collections::HashMap;
|
|
|
|
|
2022-08-28 19:39:28 +02:00
|
|
|
use actix_web::{
|
|
|
|
body::BoxBody,
|
|
|
|
dev::ServiceResponse,
|
|
|
|
error,
|
|
|
|
http::{header::ContentType, StatusCode},
|
|
|
|
middleware,
|
|
|
|
middleware::{ErrorHandlerResponse, ErrorHandlers},
|
|
|
|
web, App, Error, HttpResponse, HttpServer, Result,
|
|
|
|
};
|
2020-09-10 22:34:32 +02:00
|
|
|
use serde_json::json;
|
|
|
|
use tinytemplate::TinyTemplate;
|
|
|
|
|
|
|
|
// store tiny_template in application state
|
|
|
|
async fn index(
|
|
|
|
tmpl: web::Data<TinyTemplate<'_>>,
|
|
|
|
query: web::Query<HashMap<String, String>>,
|
|
|
|
) -> Result<HttpResponse, Error> {
|
|
|
|
let s = if let Some(name) = query.get("name") {
|
|
|
|
// submitted form
|
|
|
|
let ctx = json!({
|
|
|
|
"name" : name.to_owned(),
|
|
|
|
"text" : "Welcome!".to_owned()
|
|
|
|
});
|
|
|
|
tmpl.render("user.html", &ctx)
|
|
|
|
.map_err(|_| error::ErrorInternalServerError("Template error"))?
|
|
|
|
} else {
|
|
|
|
tmpl.render("index.html", &serde_json::Value::Null)
|
|
|
|
.map_err(|_| error::ErrorInternalServerError("Template error"))?
|
|
|
|
};
|
|
|
|
Ok(HttpResponse::Ok().content_type("text/html").body(s))
|
|
|
|
}
|
|
|
|
|
2020-11-30 09:54:00 +01:00
|
|
|
#[actix_web::main]
|
2020-09-10 22:34:32 +02:00
|
|
|
async fn main() -> std::io::Result<()> {
|
2023-03-14 04:11:49 +01:00
|
|
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
|
|
|
|
|
|
|
log::info!("starting HTTP server at http://localhost:8080");
|
2020-09-10 22:34:32 +02:00
|
|
|
|
|
|
|
HttpServer::new(|| {
|
|
|
|
let mut tt = TinyTemplate::new();
|
|
|
|
tt.add_template("index.html", INDEX).unwrap();
|
|
|
|
tt.add_template("user.html", USER).unwrap();
|
|
|
|
tt.add_template("error.html", ERROR).unwrap();
|
|
|
|
|
|
|
|
App::new()
|
2022-02-02 16:18:48 +01:00
|
|
|
.app_data(web::Data::new(tt))
|
2023-03-14 04:11:49 +01:00
|
|
|
.wrap(middleware::Logger::default())
|
2020-09-10 22:34:32 +02:00
|
|
|
.service(web::resource("/").route(web::get().to(index)))
|
|
|
|
.service(web::scope("").wrap(error_handlers()))
|
|
|
|
})
|
2022-02-17 21:22:36 +01:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
2020-09-10 22:34:32 +02:00
|
|
|
.run()
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
|
|
|
// Custom error handlers, to return HTML responses when an error occurs.
|
2022-02-02 16:18:48 +01:00
|
|
|
fn error_handlers() -> ErrorHandlers<BoxBody> {
|
2020-09-10 22:34:32 +02:00
|
|
|
ErrorHandlers::new().handler(StatusCode::NOT_FOUND, not_found)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error handler for a 404 Page not found error.
|
2022-02-02 16:18:48 +01:00
|
|
|
fn not_found<B>(res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<BoxBody>> {
|
2020-09-10 22:34:32 +02:00
|
|
|
let response = get_error_response(&res, "Page not found");
|
2022-02-02 16:18:48 +01:00
|
|
|
Ok(ErrorHandlerResponse::Response(ServiceResponse::new(
|
|
|
|
res.into_parts().0,
|
|
|
|
response.map_into_left_body(),
|
|
|
|
)))
|
2020-09-10 22:34:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Generic error handler.
|
2022-02-02 16:18:48 +01:00
|
|
|
fn get_error_response<B>(res: &ServiceResponse<B>, error: &str) -> HttpResponse {
|
2020-09-10 22:34:32 +02:00
|
|
|
let request = res.request();
|
|
|
|
|
|
|
|
// Provide a fallback to a simple plain text response in case an error occurs during the
|
|
|
|
// rendering of the error page.
|
2023-07-09 04:32:47 +02:00
|
|
|
let fallback = |err: &str| {
|
2022-02-02 16:18:48 +01:00
|
|
|
HttpResponse::build(res.status())
|
|
|
|
.content_type(ContentType::plaintext())
|
2023-07-09 04:32:47 +02:00
|
|
|
.body(err.to_string())
|
2020-09-10 22:34:32 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
let tt = request
|
|
|
|
.app_data::<web::Data<TinyTemplate<'_>>>()
|
|
|
|
.map(|t| t.get_ref());
|
|
|
|
match tt {
|
|
|
|
Some(tt) => {
|
|
|
|
let mut context = std::collections::HashMap::new();
|
|
|
|
context.insert("error", error.to_owned());
|
|
|
|
context.insert("status_code", res.status().as_str().to_owned());
|
|
|
|
let body = tt.render("error.html", &context);
|
|
|
|
|
|
|
|
match body {
|
2022-02-02 16:18:48 +01:00
|
|
|
Ok(body) => HttpResponse::build(res.status())
|
|
|
|
.content_type(ContentType::html())
|
2020-09-10 22:34:32 +02:00
|
|
|
.body(body),
|
|
|
|
Err(_) => fallback(error),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
None => fallback(error),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static ERROR: &str = include_str!("../templates/error.html");
|
|
|
|
static INDEX: &str = include_str!("../templates/index.html");
|
|
|
|
static USER: &str = include_str!("../templates/user.html");
|