Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Upgrade to Actix Web 4 #638

Merged
merged 2 commits into from
Apr 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest]
path: [basic, actix_example, actix4_example, axum_example, axum-graphql_example, rocket_example, poem_example, jsonrpsee_example]
path: [basic, actix_example, actix3_example, axum_example, axum-graphql_example, rocket_example, poem_example, jsonrpsee_example]
steps:
- uses: actions/checkout@v2

Expand Down
3 changes: 3 additions & 0 deletions examples/actix3_example/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
HOST=127.0.0.1
PORT=8000
DATABASE_URL="mysql://root:root@localhost/actix_example"
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "sea-orm-actix-4-beta-example"
name = "sea-orm-actix-example"
version = "0.1.0"
authors = ["Sam Samai <sam@studio2pi.com.au>"]
edition = "2021"
Expand All @@ -9,12 +9,12 @@ publish = false
members = [".", "entity", "migration"]

[dependencies]
actix-files = "0.6.0-beta.4"
actix-http = "=3.0.0-beta.5"
actix-rt = "2.2.0"
actix-service = "=2.0.0-beta.5"
actix-web = "=4.0.0-beta.5"

actix-http = "2"
actix-web = "3"
actix-flash = "0.2"
actix-files = "0.5"
futures = { version = "^0.3" }
futures-util = { version = "^0.3" }
tera = "1.8.0"
dotenv = "0.15"
listenfd = "0.3.3"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
![screenshot](Screenshot.png)

# Actix 4 Beta with SeaORM example app
# Actix 3 with SeaORM example app

> Actix Web 3 has been superseeded by [Actix Web 4](https://github.com/actix/actix-web).

1. Modify the `DATABASE_URL` var in `.env` to point to your chosen database

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ version = "^0.7.0"
features = [
"macros",
"debug-print",
"runtime-actix-native-tls",
"runtime-async-std-native-tls",
"sqlx-mysql",
# "sqlx-postgres",
# "sqlx-sqlite",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use actix_files::Files as Fs;
use actix_files as fs;
use actix_web::{
error, get, middleware, post, web, App, Error, HttpRequest, HttpResponse, HttpServer, Result,
};
Expand Down Expand Up @@ -34,7 +34,11 @@ struct FlashData {
}

#[get("/")]
async fn list(req: HttpRequest, data: web::Data<AppState>) -> Result<HttpResponse, Error> {
async fn list(
req: HttpRequest,
data: web::Data<AppState>,
opt_flash: Option<actix_flash::Message<FlashData>>,
) -> Result<HttpResponse, Error> {
let template = &data.templates;
let conn = &data.conn;

Expand All @@ -58,6 +62,11 @@ async fn list(req: HttpRequest, data: web::Data<AppState>) -> Result<HttpRespons
ctx.insert("posts_per_page", &posts_per_page);
ctx.insert("num_pages", &num_pages);

if let Some(flash) = opt_flash {
let flash_inner = flash.into_inner();
ctx.insert("flash", &flash_inner);
}

let body = template
.render("index.html.tera", &ctx)
.map_err(|_| error::ErrorInternalServerError("Template error"))?;
Expand All @@ -78,7 +87,7 @@ async fn new(data: web::Data<AppState>) -> Result<HttpResponse, Error> {
async fn create(
data: web::Data<AppState>,
post_form: web::Form<post::Model>,
) -> Result<HttpResponse, Error> {
) -> actix_flash::Response<HttpResponse, FlashData> {
let conn = &data.conn;

let form = post_form.into_inner();
Expand All @@ -92,9 +101,12 @@ async fn create(
.await
.expect("could not insert post");

Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
let flash = FlashData {
kind: "success".to_owned(),
message: "Post successfully added.".to_owned(),
};

actix_flash::Response::with_redirect(flash, "/")
}

#[get("/{id}")]
Expand Down Expand Up @@ -122,7 +134,7 @@ async fn update(
data: web::Data<AppState>,
id: web::Path<i32>,
post_form: web::Form<post::Model>,
) -> Result<HttpResponse, Error> {
) -> actix_flash::Response<HttpResponse, FlashData> {
let conn = &data.conn;
let form = post_form.into_inner();

Expand All @@ -135,13 +147,19 @@ async fn update(
.await
.expect("could not edit post");

Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
let flash = FlashData {
kind: "success".to_owned(),
message: "Post successfully updated.".to_owned(),
};

actix_flash::Response::with_redirect(flash, "/")
}

#[post("/delete/{id}")]
async fn delete(data: web::Data<AppState>, id: web::Path<i32>) -> Result<HttpResponse, Error> {
async fn delete(
data: web::Data<AppState>,
id: web::Path<i32>,
) -> actix_flash::Response<HttpResponse, FlashData> {
let conn = &data.conn;

let post: post::ActiveModel = Post::find_by_id(id.into_inner())
Expand All @@ -153,9 +171,12 @@ async fn delete(data: web::Data<AppState>, id: web::Path<i32>) -> Result<HttpRes

post.delete(conn).await.unwrap();

Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
let flash = FlashData {
kind: "success".to_owned(),
message: "Post successfully deleted.".to_owned(),
};

actix_flash::Response::with_redirect(flash, "/")
}

#[actix_web::main]
Expand All @@ -179,10 +200,11 @@ async fn main() -> std::io::Result<()> {
let mut listenfd = ListenFd::from_env();
let mut server = HttpServer::new(move || {
App::new()
.service(Fs::new("/static", "./static"))
.data(state.clone())
.wrap(middleware::Logger::default()) // enable logger
.wrap(actix_flash::Flash::default())
.configure(init)
.service(fs::Files::new("/static", "./static").show_files_listing())
});

server = match listenfd.take_tcp_listener(0)? {
Expand Down
3 changes: 0 additions & 3 deletions examples/actix4_example/.env

This file was deleted.

2 changes: 1 addition & 1 deletion examples/actix_example/.env
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
HOST=127.0.0.1
PORT=8000
DATABASE_URL="mysql://root:root@localhost/actix_example"
DATABASE_URL="mysql://root:root@localhost/actix_example"
18 changes: 9 additions & 9 deletions examples/actix_example/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "sea-orm-actix-example"
name = "sea-orm-actix-4-beta-example"
version = "0.1.0"
authors = ["Sam Samai <sam@studio2pi.com.au>"]
edition = "2021"
Expand All @@ -9,15 +9,15 @@ publish = false
members = [".", "entity", "migration"]

[dependencies]
actix-http = "2"
actix-web = "3"
actix-flash = "0.2"
actix-files = "0.5"
futures = { version = "^0.3" }
futures-util = { version = "^0.3" }
tera = "1.8.0"
actix-files = "0.6"
actix-http = "3"
actix-rt = "2.7"
actix-service = "2"
actix-web = "4"

tera = "1.15.0"
dotenv = "0.15"
listenfd = "0.3.3"
listenfd = "0.5"
serde = "1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
entity = { path = "entity" }
Expand Down
2 changes: 1 addition & 1 deletion examples/actix_example/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
![screenshot](Screenshot.png)

# Actix with SeaORM example app
# Actix 4 with SeaORM example app

1. Modify the `DATABASE_URL` var in `.env` to point to your chosen database

Expand Down
2 changes: 1 addition & 1 deletion examples/actix_example/entity/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ version = "^0.7.0"
features = [
"macros",
"debug-print",
"runtime-async-std-native-tls",
"runtime-actix-native-tls",
"sqlx-mysql",
# "sqlx-postgres",
# "sqlx-sqlite",
Expand Down
63 changes: 23 additions & 40 deletions examples/actix_example/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use actix_files as fs;
use actix_files::Files as Fs;
use actix_web::{
error, get, middleware, post, web, App, Error, HttpRequest, HttpResponse, HttpServer, Result,
error, get, middleware, post, web, App, Error, HttpRequest, HttpResponse, HttpServer, Result
};

use entity::post;
Expand All @@ -21,6 +21,7 @@ struct AppState {
templates: tera::Tera,
conn: DatabaseConnection,
}

#[derive(Debug, Deserialize)]
pub struct Params {
page: Option<usize>,
Expand All @@ -34,11 +35,7 @@ struct FlashData {
}

#[get("/")]
async fn list(
req: HttpRequest,
data: web::Data<AppState>,
opt_flash: Option<actix_flash::Message<FlashData>>,
) -> Result<HttpResponse, Error> {
async fn list(req: HttpRequest, data: web::Data<AppState>) -> Result<HttpResponse, Error> {
let template = &data.templates;
let conn = &data.conn;

Expand All @@ -62,11 +59,6 @@ async fn list(
ctx.insert("posts_per_page", &posts_per_page);
ctx.insert("num_pages", &num_pages);

if let Some(flash) = opt_flash {
let flash_inner = flash.into_inner();
ctx.insert("flash", &flash_inner);
}

let body = template
.render("index.html.tera", &ctx)
.map_err(|_| error::ErrorInternalServerError("Template error"))?;
Expand All @@ -87,7 +79,7 @@ async fn new(data: web::Data<AppState>) -> Result<HttpResponse, Error> {
async fn create(
data: web::Data<AppState>,
post_form: web::Form<post::Model>,
) -> actix_flash::Response<HttpResponse, FlashData> {
) -> Result<HttpResponse, Error> {
let conn = &data.conn;

let form = post_form.into_inner();
Expand All @@ -101,12 +93,9 @@ async fn create(
.await
.expect("could not insert post");

let flash = FlashData {
kind: "success".to_owned(),
message: "Post successfully added.".to_owned(),
};

actix_flash::Response::with_redirect(flash, "/")
Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
}

#[get("/{id}")]
Expand Down Expand Up @@ -134,7 +123,7 @@ async fn update(
data: web::Data<AppState>,
id: web::Path<i32>,
post_form: web::Form<post::Model>,
) -> actix_flash::Response<HttpResponse, FlashData> {
) -> Result<HttpResponse, Error> {
let conn = &data.conn;
let form = post_form.into_inner();

Expand All @@ -147,19 +136,13 @@ async fn update(
.await
.expect("could not edit post");

let flash = FlashData {
kind: "success".to_owned(),
message: "Post successfully updated.".to_owned(),
};

actix_flash::Response::with_redirect(flash, "/")
Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
}

#[post("/delete/{id}")]
async fn delete(
data: web::Data<AppState>,
id: web::Path<i32>,
) -> actix_flash::Response<HttpResponse, FlashData> {
async fn delete(data: web::Data<AppState>, id: web::Path<i32>) -> Result<HttpResponse, Error> {
let conn = &data.conn;

let post: post::ActiveModel = Post::find_by_id(id.into_inner())
Expand All @@ -171,12 +154,9 @@ async fn delete(

post.delete(conn).await.unwrap();

let flash = FlashData {
kind: "success".to_owned(),
message: "Post successfully deleted.".to_owned(),
};

actix_flash::Response::with_redirect(flash, "/")
Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
}

#[actix_web::main]
Expand All @@ -191,20 +171,23 @@ async fn main() -> std::io::Result<()> {
let port = env::var("PORT").expect("PORT is not set in .env file");
let server_url = format!("{}:{}", host, port);

// create post table if not exists
// establish connection to database and apply migrations
// -> create post table if not exists
let conn = sea_orm::Database::connect(&db_url).await.unwrap();
Migrator::up(&conn, None).await.unwrap();

// load tera templates and build app state
let templates = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
let state = AppState { templates, conn };

// create server and try to serve over socket if possible
let mut listenfd = ListenFd::from_env();
let mut server = HttpServer::new(move || {
App::new()
.data(state.clone())
.service(Fs::new("/static", "./static"))
.app_data(web::Data::new(state.clone()))
.wrap(middleware::Logger::default()) // enable logger
.wrap(actix_flash::Flash::default())
.configure(init)
.service(fs::Files::new("/static", "./static").show_files_listing())
});

server = match listenfd.take_tcp_listener(0)? {
Expand Down