A very performant and light (2mb in memory) link shortener and tracker. Written in Rust and React and uses Postgres/SQLite.
1use actix_cors::Cors; 2use actix_files as fs; 3use actix_web::{web, App, HttpServer}; 4use anyhow::Result; 5use simplelink::check_and_generate_admin_token; 6use simplelink::{handlers, AppState}; 7use sqlx::postgres::PgPoolOptions; 8use tracing::info; 9 10#[actix_web::main] 11async fn main() -> Result<()> { 12 // Load environment variables from .env file 13 dotenv::dotenv().ok(); 14 15 // Initialize logging 16 tracing_subscriber::fmt::init(); 17 18 // Database connection string from environment 19 let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set"); 20 21 // Create database connection pool 22 let pool = PgPoolOptions::new() 23 .max_connections(5) 24 .acquire_timeout(std::time::Duration::from_secs(3)) 25 .connect(&database_url) 26 .await?; 27 28 // Run database migrations 29 sqlx::migrate!("./migrations").run(&pool).await?; 30 31 let admin_token = check_and_generate_admin_token(&pool).await?; 32 33 let state = AppState { 34 db: pool, 35 admin_token, 36 }; 37 38 let host = std::env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()); 39 let port = std::env::var("SERVER_PORT").unwrap_or_else(|_| "8080".to_string()); 40 info!("Starting server at http://{}:{}", host, port); 41 42 // Start HTTP server 43 HttpServer::new(move || { 44 let cors = Cors::default() 45 .allow_any_origin() 46 .allow_any_method() 47 .allow_any_header() 48 .max_age(3600); 49 50 App::new() 51 .wrap(cors) 52 .app_data(web::Data::new(state.clone())) 53 .service( 54 web::scope("/api") 55 .route("/shorten", web::post().to(handlers::create_short_url)) 56 .route("/links", web::get().to(handlers::get_all_links)) 57 .route("/links/{id}", web::delete().to(handlers::delete_link)) 58 .route( 59 "/links/{id}/clicks", 60 web::get().to(handlers::get_link_clicks), 61 ) 62 .route( 63 "/links/{id}/sources", 64 web::get().to(handlers::get_link_sources), 65 ) 66 .route("/auth/register", web::post().to(handlers::register)) 67 .route("/auth/login", web::post().to(handlers::login)) 68 .route("/health", web::get().to(handlers::health_check)), 69 ) 70 .service(web::resource("/{short_code}").route(web::get().to(handlers::redirect_to_url))) 71 .service(fs::Files::new("/", "./static").index_file("index.html")) 72 }) 73 .workers(2) 74 .backlog(10_000) 75 .bind(format!("{}:{}", host, port))? 76 .run() 77 .await?; 78 79 Ok(()) 80}