1
0
mirror of https://github.com/actix/examples synced 2025-06-26 09:17:41 +02:00
This commit is contained in:
Rob Ede
2022-07-09 21:05:06 +01:00
parent e97bc83f59
commit 4b801ba222
10 changed files with 55 additions and 42 deletions

View File

@ -43,7 +43,9 @@ async fn welcome(req: HttpRequest, session: Session) -> Result<HttpResponse> {
async fn default_handler(req_method: Method) -> Result<impl Responder> {
match req_method {
Method::GET => {
let file = NamedFile::open("static/404.html")?.set_status_code(StatusCode::NOT_FOUND);
let file = NamedFile::open("static/404.html")?
.customize()
.with_status(StatusCode::NOT_FOUND);
Ok(Either::Left(file))
}
_ => Ok(Either::Right(HttpResponse::MethodNotAllowed().finish())),

View File

@ -4,9 +4,10 @@ version = "1.0.0"
edition = "2021"
[dependencies]
actix-web = "4"
actix-files = "0.6"
actix-session = "0.5"
actix-web = "4"
actix-web-lab = "0.16"
dotenv = "0.15"
env_logger = "0.9"

View File

@ -1,8 +1,9 @@
use actix_files::NamedFile;
use actix_session::Session;
use actix_web::{
dev, error, http, middleware::ErrorHandlerResponse, web, Error, HttpResponse, Result,
dev, error, middleware::ErrorHandlerResponse, web, Error, HttpResponse, Responder, Result,
};
use actix_web_lab::web::Redirect;
use serde::Deserialize;
use sqlx::SqlitePool;
use tera::{Context, Tera};
@ -24,8 +25,7 @@ pub async fn index(
let mut context = Context::new();
context.insert("tasks", &tasks);
//Session is set during operations on other endpoints
//that can redirect to index
// Session is set during operations on other endpoints that can redirect to index
if let Some(flash) = session::get_flash(&session)? {
context.insert("msg", &(flash.kind, flash.message));
session::clear_flash(&session);
@ -38,7 +38,7 @@ pub async fn index(
Ok(HttpResponse::Ok().body(rendered))
}
#[derive(Deserialize)]
#[derive(Debug, Deserialize)]
pub struct CreateForm {
description: String,
}
@ -47,25 +47,27 @@ pub async fn create(
params: web::Form<CreateForm>,
pool: web::Data<SqlitePool>,
session: Session,
) -> Result<HttpResponse, Error> {
) -> Result<impl Responder, Error> {
if params.description.is_empty() {
session::set_flash(&session, FlashMessage::error("Description cannot be empty"))?;
Ok(redirect_to("/"))
Ok(Redirect::to("/"))
} else {
db::create_task(params.into_inner().description, &pool)
.await
.map_err(error::ErrorInternalServerError)?;
session::set_flash(&session, FlashMessage::success("Task successfully added"))?;
Ok(redirect_to("/"))
Ok(Redirect::to("/"))
}
}
#[derive(Deserialize)]
#[derive(Debug, Deserialize)]
pub struct UpdateParams {
id: i32,
}
#[derive(Deserialize)]
#[derive(Debug, Deserialize)]
pub struct UpdateForm {
_method: String,
}
@ -75,65 +77,71 @@ pub async fn update(
params: web::Path<UpdateParams>,
form: web::Form<UpdateForm>,
session: Session,
) -> Result<HttpResponse, Error> {
match form._method.as_ref() {
"put" => toggle(db, params).await,
"delete" => delete(db, params, session).await,
) -> Result<impl Responder, Error> {
Ok(Redirect::to(match form._method.as_ref() {
"put" => toggle(db, params).await?,
"delete" => delete(db, params, session).await?,
unsupported_method => {
let msg = format!("Unsupported HTTP method: {unsupported_method}");
Err(error::ErrorBadRequest(msg))
return Err(error::ErrorBadRequest(msg));
}
}
}))
}
async fn toggle(
pool: web::Data<SqlitePool>,
params: web::Path<UpdateParams>,
) -> Result<HttpResponse, Error> {
) -> Result<&'static str, Error> {
db::toggle_task(params.id, &pool)
.await
.map_err(error::ErrorInternalServerError)?;
Ok(redirect_to("/"))
Ok("/")
}
async fn delete(
pool: web::Data<SqlitePool>,
params: web::Path<UpdateParams>,
session: Session,
) -> Result<HttpResponse, Error> {
) -> Result<&'static str, Error> {
db::delete_task(params.id, &pool)
.await
.map_err(error::ErrorInternalServerError)?;
session::set_flash(&session, FlashMessage::success("Task was deleted."))?;
Ok(redirect_to("/"))
}
fn redirect_to(location: &str) -> HttpResponse {
HttpResponse::Found()
.append_header((http::header::LOCATION, location))
.finish()
session::set_flash(&session, FlashMessage::success("Task was deleted."))?;
Ok("/")
}
pub fn bad_request<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
let new_resp = NamedFile::open("static/errors/400.html")?
.set_status_code(res.status())
.into_response(res.request())
.customize()
.with_status(res.status())
.respond_to(res.request())
.map_into_boxed_body()
.map_into_right_body();
Ok(ErrorHandlerResponse::Response(res.into_response(new_resp)))
}
pub fn not_found<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
let new_resp = NamedFile::open("static/errors/404.html")?
.set_status_code(res.status())
.into_response(res.request())
.customize()
.with_status(res.status())
.respond_to(res.request())
.map_into_boxed_body()
.map_into_right_body();
Ok(ErrorHandlerResponse::Response(res.into_response(new_resp)))
}
pub fn internal_server_error<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
let new_resp = NamedFile::open("static/errors/500.html")?
.set_status_code(res.status())
.into_response(res.request())
.customize()
.with_status(res.status())
.respond_to(res.request())
.map_into_boxed_body()
.map_into_right_body();
Ok(ErrorHandlerResponse::Response(res.into_response(new_resp)))
}