1
0
mirror of https://github.com/actix/examples synced 2024-11-30 17:14:35 +01:00
examples/templating/tinytemplate/src/main.rs

108 lines
3.5 KiB
Rust
Raw Normal View History

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,
};
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))
}
Update `tiny_template` example and deps (#388) * Update actix crates in tiny_template example * Run `cargo update` Updating crates.io index Updating git repository `https://github.com/bcmyers/argonautica` Updating actix-cors v0.5.0 -> v0.5.3 Updating actix-http v2.1.0 -> v2.2.0 Updating actix-web v3.2.0 -> v3.3.1 Updating addr2line v0.13.0 -> v0.14.0 Updating aes v0.4.0 -> v0.6.0 Updating aes-gcm v0.6.0 -> v0.8.0 Updating aes-soft v0.4.0 -> v0.6.4 Updating aesni v0.7.0 -> v0.10.0 Updating ahash v0.3.8 -> v0.4.6 Updating aho-corasick v0.7.14 -> v0.7.15 Updating anyhow v1.0.33 -> v1.0.34 Removing arc-swap v0.4.7 Updating arrayvec v0.5.1 -> v0.5.2 Updating async-executor v1.3.0 -> v1.4.0 Updating async-global-executor v1.3.0 -> v1.4.3 Updating async-graphql v2.0.0 -> v2.1.5 Updating async-graphql-actix-web v2.0.0 -> v2.1.5 Updating async-graphql-derive v2.0.0 -> v2.1.4 Updating async-graphql-parser v2.0.0 -> v2.1.2 Updating async-graphql-value v2.0.0 -> v2.0.5 Updating async-io v1.1.10 -> v1.3.0 Updating async-std v1.6.5 -> v1.7.0 Updating async-task v4.0.2 -> v4.0.3 Updating async-trait v0.1.41 -> v0.1.42 Updating awc v2.0.0 -> v2.0.3 Updating backtrace v0.3.53 -> v0.3.55 Updating base-x v0.2.6 -> v0.2.8 Updating blake2b_simd v0.5.10 -> v0.5.11 Removing block-cipher v0.7.1 Updating bstr v0.2.13 -> v0.2.14 Updating cc v1.0.61 -> v1.0.65 Adding cipher v0.2.5 Updating combine v4.3.2 -> v4.4.0 Adding console_error_panic_hook v0.1.6 Updating const_fn v0.4.2 -> v0.4.3 Updating cookie v0.14.2 -> v0.14.3 Updating core-foundation v0.7.0 -> v0.9.1 Updating core-foundation-sys v0.7.0 -> v0.8.2 Updating crc32fast v1.2.0 -> v1.2.1 Adding crossbeam-utils v0.8.1 Removing crypto-mac v0.8.0 Adding crypto-mac v0.9.1 Adding crypto-mac v0.10.0 Adding ctr v0.6.0 Updating derive_utils v0.10.0 -> v0.11.0 Updating encoding_rs v0.8.24 -> v0.8.26 Updating env_logger v0.8.1 -> v0.8.2 Updating flate2 v1.0.18 -> v1.0.19 Adding form_urlencoded v1.0.0 Updating futures v0.3.6 -> v0.3.8 Updating futures-executor v0.3.6 -> v0.3.8 Updating futures-lite v1.11.1 -> v1.11.2 Updating gimli v0.22.0 -> v0.23.0 Updating globset v0.4.5 -> v0.4.6 Updating h2 v0.2.6 -> v0.2.7 Updating handlebars v3.5.0 -> v3.5.1 Removing hashbrown v0.8.2 Updating hkdf v0.9.0 -> v0.10.0 Removing hmac v0.8.1 Adding hmac v0.9.0 Adding hmac v0.10.1 Updating hyper v0.13.8 -> v0.13.9 Updating ignore v0.4.16 -> v0.4.17 Updating instant v0.1.7 -> v0.1.9 Updating io-enum v0.2.3 -> v0.2.4 Removing itertools v0.9.0 Updating libc v0.2.79 -> v0.2.80 Updating lock_api v0.4.1 -> v0.4.2 Updating lru v0.6.0 -> v0.6.1 Updating memchr v2.3.3 -> v2.3.4 Removing miow v0.2.1 Removing miow v0.3.5 Adding miow v0.2.2 Adding miow v0.3.6 Updating native-tls v0.2.4 -> v0.2.6 Updating net2 v0.2.35 -> v0.2.36 Updating num-integer v0.1.43 -> v0.1.44 Updating num-traits v0.2.12 -> v0.2.14 Updating object v0.21.1 -> v0.22.0 Updating once_cell v1.4.1 -> v1.5.2 Updating onig v6.1.0 -> v6.1.1 Updating onig_sys v69.5.1 -> v69.6.0 Updating parking_lot v0.11.0 -> v0.11.1 Updating pin-project v1.0.1 -> v1.0.2 Updating pin-project-internal v1.0.1 -> v1.0.2 Removing pin-project-lite v0.1.10 Adding pin-project-lite v0.1.11 Adding pin-project-lite v0.2.0 Updating pkg-config v0.3.18 -> v0.3.19 Updating polling v2.0.1 -> v2.0.2 Updating polyval v0.4.1 -> v0.4.2 Updating postgres-protocol v0.5.2 -> v0.5.3 Updating postgres-types v0.1.2 -> v0.1.3 Updating ppv-lite86 v0.2.9 -> v0.2.10 Updating redis-async v0.6.3 -> v0.6.6 Updating regex v1.4.0 -> v1.4.2 Updating regex-syntax v0.6.19 -> v0.6.21 Updating reqwest v0.10.8 -> v0.10.9 Updating resolv-conf v0.6.3 -> v0.7.0 Updating ring v0.16.15 -> v0.16.18 Updating rust-argon2 v0.8.2 -> v0.8.3 Updating rustc-demangle v0.1.17 -> v0.1.18 Adding scoped-tls v1.0.0 Updating security-framework v0.4.4 -> v2.0.0 Updating security-framework-sys v0.4.3 -> v2.0.0 Updating serde v1.0.116 -> v1.0.117 Updating serde_derive v1.0.116 -> v1.0.117 Updating serde_urlencoded v0.6.1 -> v0.7.0 Updating sha-1 v0.9.1 -> v0.9.2 Updating sha2 v0.9.1 -> v0.9.2 Updating signal-hook-registry v1.2.1 -> v1.2.2 Updating smallvec v1.4.2 -> v1.5.0 Updating socket2 v0.3.15 -> v0.3.17 Adding spin v0.6.0 Updating standback v0.2.11 -> v0.2.13 Updating string_cache v0.8.0 -> v0.8.1 Updating syn v1.0.44 -> v1.0.53 Updating termcolor v1.1.0 -> v1.1.2 Updating terminal_size v0.1.13 -> v0.1.15 Updating thiserror v1.0.21 -> v1.0.22 Updating thiserror-impl v1.0.21 -> v1.0.22 Updating time v0.2.22 -> v0.2.23 Removing tinyvec v0.3.4 Removing tinyvec v1.0.1 Adding tinyvec v1.1.0 Updating tokio v0.2.22 -> v0.2.23 Updating tokio-macros v0.2.5 -> v0.2.6 Updating tracing v0.1.21 -> v0.1.22 Adding tracing-futures v0.2.4 Updating trust-dns-proto v0.19.5 -> v0.19.6 Updating trust-dns-resolver v0.19.5 -> v0.19.6 Updating twox-hash v1.5.0 -> v1.6.0 Updating unicode-normalization v0.1.13 -> v0.1.16 Updating unicode-segmentation v1.6.0 -> v1.7.1 Updating url v2.1.1 -> v2.2.0 Updating v_escape v0.14.0 -> v0.14.1 Adding wasm-bindgen-test v0.3.18 Adding wasm-bindgen-test-macro v0.3.18 Updating wepoll-sys v3.0.0 -> v3.0.1
2020-11-30 09:54:00 +01:00
#[actix_web::main]
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");
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()
.app_data(web::Data::new(tt))
2023-03-14 04:11:49 +01:00
.wrap(middleware::Logger::default())
.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))?
.run()
.await
}
// Custom error handlers, to return HTML responses when an error occurs.
fn error_handlers() -> ErrorHandlers<BoxBody> {
ErrorHandlers::new().handler(StatusCode::NOT_FOUND, not_found)
}
// Error handler for a 404 Page not found error.
fn not_found<B>(res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<BoxBody>> {
let response = get_error_response(&res, "Page not found");
Ok(ErrorHandlerResponse::Response(ServiceResponse::new(
res.into_parts().0,
response.map_into_left_body(),
)))
}
// Generic error handler.
fn get_error_response<B>(res: &ServiceResponse<B>, error: &str) -> HttpResponse {
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.
let fallback = |e: &str| {
HttpResponse::build(res.status())
.content_type(ContentType::plaintext())
.body(e.to_string())
};
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 {
Ok(body) => HttpResponse::build(res.status())
.content_type(ContentType::html())
.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");