1
0
mirror of https://github.com/actix/examples synced 2025-02-13 14:02:19 +01:00

47 lines
1.1 KiB
Rust
Raw Normal View History

2018-05-08 11:08:43 -07:00
use std::collections::HashMap;
2023-03-14 03:11:49 +00:00
use actix_web::{middleware, web, App, HttpServer, Responder, Result};
2018-04-24 09:12:48 -07:00
use askama::Template;
#[derive(Template)]
#[template(path = "user.html")]
struct UserTemplate<'a> {
name: &'a str,
text: &'a str,
}
#[derive(Template)]
#[template(path = "index.html")]
struct Index;
2023-03-14 03:11:49 +00:00
async fn index(query: web::Query<HashMap<String, String>>) -> Result<impl Responder> {
let html = if let Some(name) = query.get("name") {
2018-04-24 09:12:48 -07:00
UserTemplate {
2019-09-05 00:04:57 +09:00
name,
2018-04-24 09:12:48 -07:00
text: "Welcome!",
2019-03-09 18:03:09 -08:00
}
.render()
2023-03-14 03:11:49 +00:00
.expect("template should be valid")
2018-04-24 09:12:48 -07:00
} else {
2023-03-14 03:11:49 +00:00
Index.render().expect("template should be valid")
2018-04-24 09:12:48 -07:00
};
2023-03-14 03:11:49 +00:00
2024-07-07 00:23:03 +01:00
Ok(web::Html::new(html))
2018-04-24 09:12:48 -07:00
}
2020-09-12 16:49:45 +01:00
#[actix_web::main]
2019-12-07 23:59:24 +06:00
async fn main() -> std::io::Result<()> {
2023-03-14 03:11:49 +00:00
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
log::info!("starting HTTP server at http://localhost:8080");
2019-03-09 22:38:15 -08:00
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.service(web::resource("/").route(web::get().to(index)))
2019-03-09 18:03:09 -08:00
})
2022-02-17 20:22:36 +00:00
.bind(("127.0.0.1", 8080))?
2019-12-25 20:48:33 +04:00
.run()
2019-12-07 23:59:24 +06:00
.await
2018-04-24 09:12:48 -07:00
}