use actix_web::{get, post, web, App, HttpServer, HttpResponse}; use askama::Template; use askama_actix::TemplateToResponse; use sqlx::{Row, SqlitePool}; #[derive(Template)] #[template(path = "hello.html")] struct HelloTemplate { name: String, } #[get("/hello/{name}")] async fn hello(name: web::Path<String>) -> HttpResponse { let hello = HelloTemplate { name: name.into_inner(), }; hello.to_response() } #[derive(Template)] #[template(path = "todo.html")] struct TodoTemplate { tasks: Vec<String>, } #[derive(serde::Deserialize)] struct Task { id: String, } #[post("/update")] async fn update(pool: web::Data<SqlitePool>, form: web::Form<Task>) -> HttpResponse { let task = form.into_inner(); sqlx::query("DELETE FROM tasks WHERE task = ?") .bind(&task.id) .execute(pool.as_ref()) .await .unwrap(); HttpResponse::Ok().finish() } #[get("/")] async fn todo(pool: web::Data<SqlitePool>) -> HttpResponse { let rows = sqlx::query("SELECT task FROM tasks;") .fetch_all(pool.as_ref()) .await .unwrap(); let tasks: Vec<String> = rows .iter() .map(|row| row.get::<String, _>("task")) .collect(); let todo = TodoTemplate { tasks }; todo.to_response() } #[actix_web::main] async fn main() -> std::io::Result<()> { let pool = SqlitePool::connect("sqlite::memory:").await.unwrap(); sqlx::query("CREATE TABLE tasks (task TEXT)") .execute(&pool) .await .unwrap(); sqlx::query("INSERT INTO tasks(task) VALUES('task1')") .execute(&pool) .await .unwrap(); sqlx::query("INSERT INTO tasks(task) VALUES('task2')") .execute(&pool) .await .unwrap(); sqlx::query("INSERT INTO tasks(task) VALUES('task3')") .execute(&pool) .await .unwrap(); HttpServer::new(move|| { App::new() .service(hello) .service(todo) .app_data(web::Data::new(pool.clone())) }) .bind(("0.0.0.0", 8080))? .run() .await }

