1
0
mirror of https://github.com/actix/examples synced 2024-12-03 18:22:14 +01:00
examples/databases/mysql/src/main.rs

69 lines
2.0 KiB
Rust
Raw Normal View History

2023-07-17 21:59:04 +02:00
use std::{env, io};
2023-07-17 21:59:04 +02:00
use actix_web::{web, App, HttpServer};
2023-07-17 18:55:17 +02:00
2023-07-17 21:59:04 +02:00
mod models;
mod persistence;
mod routes;
fn get_conn_builder(
db_user: String,
db_password: String,
db_host: String,
db_port: u16,
db_name: String,
2023-07-17 18:55:17 +02:00
) -> mysql::OptsBuilder {
mysql::OptsBuilder::new()
.ip_or_hostname(Some(db_host))
.tcp_port(db_port)
.db_name(Some(db_name))
.user(Some(db_user))
2023-07-17 18:55:17 +02:00
.pass(Some(db_password))
}
#[actix_web::main]
2023-07-17 21:59:04 +02:00
async fn main() -> io::Result<()> {
// initialize environment
2023-10-29 02:18:40 +02:00
dotenvy::dotenv().ok();
2023-07-17 21:59:04 +02:00
// initialize logger
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
log::info!("setting up app from environment");
let db_user = env::var("MYSQL_USER").expect("MYSQL_USER is not set in .env file");
let db_password = env::var("MYSQL_PASSWORD").expect("MYSQL_PASSWORD is not set in .env file");
let db_host = env::var("MYSQL_HOST").expect("MYSQL_HOST is not set in .env file");
2023-07-17 21:59:04 +02:00
let db_port = env::var("MYSQL_PORT").expect("MYSQL_PORT is not set in .env file");
let db_name = env::var("MYSQL_DBNAME").expect("MYSQL_DBNAME is not set in .env file");
2023-07-17 21:59:04 +02:00
let db_port = db_port.parse().unwrap();
2023-07-17 21:59:04 +02:00
let builder = get_conn_builder(db_user, db_password, db_host, db_port, db_name);
2023-07-17 21:59:04 +02:00
log::info!("initializing database connection");
let pool = mysql::Pool::new(builder).unwrap();
let shared_data = web::Data::new(pool);
2023-07-17 21:59:04 +02:00
log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(move || {
App::new()
.app_data(shared_data.clone())
2023-07-17 21:59:04 +02:00
.service(routes::index)
.service(routes::add_bank)
.service(routes::add_branch)
.service(routes::add_teller)
.service(routes::add_customer)
.service(routes::get_bank)
.service(routes::get_branch)
.service(routes::get_teller)
.service(routes::get_customer)
})
2023-07-17 21:59:04 +02:00
.bind(("127.0.0.1", 8080))?
2023-07-18 02:01:26 +02:00
.workers(2)
2023-07-17 21:59:04 +02:00
.run()
.await
}