1
0
mirror of https://github.com/actix/examples synced 2024-12-01 09:30:06 +01:00
examples/basics/todo/src/main.rs

64 lines
1.9 KiB
Rust
Raw Normal View History

2019-03-11 02:23:44 +01:00
use std::{env, io};
use actix_files::Files;
2019-03-11 02:23:44 +01:00
use actix_session::CookieSession;
use actix_web::{
http,
middleware::{ErrorHandlers, Logger},
web, App, HttpServer,
};
2018-08-27 11:56:26 +02:00
use dotenv::dotenv;
use tera::Tera;
mod api;
mod db;
mod model;
mod session;
static SESSION_SIGNING_KEY: &[u8] = &[0; 32];
2020-09-12 17:49:45 +02:00
#[actix_web::main]
2019-12-07 18:59:24 +01:00
async fn main() -> io::Result<()> {
2018-08-27 11:56:26 +02:00
dotenv().ok();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
2018-08-27 11:56:26 +02:00
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
2022-02-05 18:34:43 +01:00
let pool = db::init_pool(&database_url)
.await
.expect("Failed to create pool");
2018-08-27 11:56:26 +02:00
2022-02-06 09:19:35 +01:00
log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(move || {
log::debug!("Constructing the App");
2018-08-27 11:56:26 +02:00
2022-02-18 03:44:02 +01:00
let mut templates = Tera::new("templates/**/*").expect("errors in tera templates");
2020-09-14 18:02:57 +02:00
templates.autoescape_on(vec!["tera"]);
2018-08-27 11:56:26 +02:00
2019-03-11 02:23:44 +01:00
let session_store = CookieSession::signed(SESSION_SIGNING_KEY).secure(false);
2018-08-27 11:56:26 +02:00
let error_handlers = ErrorHandlers::new()
.handler(
http::StatusCode::INTERNAL_SERVER_ERROR,
api::internal_server_error,
)
.handler(http::StatusCode::BAD_REQUEST, api::bad_request)
.handler(http::StatusCode::NOT_FOUND, api::not_found);
2019-03-11 02:23:44 +01:00
App::new()
2022-02-05 18:34:43 +01:00
.app_data(web::Data::new(templates))
.app_data(web::Data::new(pool.clone()))
2019-03-26 04:29:00 +01:00
.wrap(Logger::default())
.wrap(session_store)
.wrap(error_handlers)
2019-12-07 18:59:24 +01:00
.service(web::resource("/").route(web::get().to(api::index)))
.service(web::resource("/todo").route(web::post().to(api::create)))
.service(web::resource("/todo/{id}").route(web::post().to(api::update)))
2022-02-18 02:44:53 +01:00
.service(Files::new("/static", "./static"))
})
2022-02-06 08:55:51 +01:00
.bind(("127.0.0.1", 8080))?
.workers(2)
.run()
.await
2018-08-27 11:56:26 +02:00
}